为什么需要工作流?在之前博文.Net依赖注入技术学习:基本模型中,有提到这个世界的基本构型是纵向分层和横向组合,而工作流模型在纵向上比源码级别提升了一个层次,它的基本操作单元是步骤;在横向上通过一些规则,可以使步骤灵活组合。实现了更高层次抽象的简洁性和表达力的平衡。
本文介绍了.Net体系比较优秀的开源工作流WorkflowCore,github地址:https://github.com/danielgerlag/workflow-core。
下面定义了2个步骤:HelloWorld和GoodbyeWorld
public class HelloWorld : StepBody { public override ExecutionResult Run(IStepExecutionContext context) { Console.WriteLine("Hello world"); return ExecutionResult.Next(); } }View Code
public class GoodbyeWorld : StepBody { private ILogger _logger; public GoodbyeWorld(ILoggerFactory loggerFactory) { _logger = loggerFactory.CreateLogger<GoodbyeWorld>(); } public override ExecutionResult Run(IStepExecutionContext context) { Console.WriteLine("Goodbye world"); _logger.LogInformation("Hi there!"); return ExecutionResult.Next(); } }View Code
然后定义一个工作流:
public class HelloWorldWorkflow : IWorkflow { public void Build(IWorkflowBuilder<object> builder) { builder .StartWith<HelloWorld>() .Then<GoodbyeWorld>(); } public string Id => "HelloWorld"; public int Version => 1; }View Code
最后启动工作流:
public class Program { public static void Main(string[] args) { IServiceProvider serviceProvider = ConfigureServices(); //start the workflow host var host = serviceProvider.GetService<IWorkflowHost>(); host.RegisterWorkflow<HelloWorldWorkflow>(); host.Start(); host.StartWorkflow("HelloWorld"); Console.ReadLine(); host.Stop(); } private static IServiceProvider ConfigureServices() { //setup dependency injection IServiceCollection services = new ServiceCollection(); services.AddLogging(); services.AddWorkflow(); //services.AddWorkflow(x => x.UseMongoDB(@"mongodb://localhost:27017", "workflow")); services.AddTransient<GoodbyeWorld>(); var serviceProvider = services.BuildServiceProvider(); return serviceProvider; } }View Code