為什么需要工作流?在之前博文.Net依賴注入技術學習:基本模型中,有提到這個世界的基本構型是縱向分層和橫向組合,而工作流模型在縱向上比源碼級別提升了一個層次,它的基本操作單元是步驟;在橫向上通過一些規則,可以使步驟靈活組合。實現了更高層次抽象的簡潔性和表達力的平衡。
本文介紹了.Net體系比較優秀的開源工作流WorkflowCore,github地址:https://github.com/danielgerlag/workflow-core。
教程參考:https://workflow-core.readthedocs.io/en/latest/
下面定義了2個步驟:HelloWorld和GoodbyeWorld
public class HelloWorld : StepBody { public override ExecutionResult Run(IStepExecutionContext context) { Console.WriteLine("Hello world"); return ExecutionResult.Next(); } }
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(); } }
然后定義一個工作流:
public class HelloWorldWorkflow : IWorkflow { public void Build(IWorkflowBuilder<object> builder) { builder .StartWith<HelloWorld>() .Then<GoodbyeWorld>(); } public string Id => "HelloWorld"; public int Version => 1; }
最后啟動工作流:
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; } }
