EventStore实现好了,接下来,我们将其用在CustomerCreatedEventHandler中,以便将订阅的CustomerCreatedEvent保存下来。
事件数据的保存
保存事件数据的第一步,就是在ASP.NET Core Web API的IoC容器中,将DapperEventStore注册进去。这一步是非常简单的,只需要在Startup.cs的ConfigureServices方法中完成即可。代码如下:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddTransient<IEventHandler, CustomerCreatedEventHandler>();
services.AddTransient<IEventStore>(serviceProvider => new DapperEventStore(Configuration[ "mssql:connectionString" ]));
services.AddSingleton<IEventBus, PassThroughEventBus>();
}
注意我们使用的是services.AddTransient方法来注册DapperEventStore,我们希望应用程序在每次请求IEventStore实例时,都能获得一个新的DapperEventStore的实例。
接下来,打开CustomerCreatedEventHandler.cs文件,在构造函数中加入对IEventStore的依赖,然后修改HandleAsync方法,在该方法中使用IEventStore的实例来完成事件数据的保存。代码如下:
public class CustomerCreatedEventHandler : IEventHandler<CustomerCreatedEvent>
{
private readonly IEventStore eventStore;
public CustomerCreatedEventHandler(IEventStore eventStore)
{
this .eventStore = eventStore;
}
public bool CanHandle(IEvent @ event )
=> @ event .GetType().Equals( typeof (CustomerCreatedEvent));
public async Task< bool > HandleAsync(CustomerCreatedEvent @ event , CancellationToken cancellationToken = default )
{
await this .eventStore.SaveEventAsync(@ event );
return true ;
}
public Task< bool > HandleAsync(IEvent @ event , CancellationToken cancellationToken = default )
=> CanHandle(@ event ) ? HandleAsync((CustomerCreatedEvent)@ event , cancellationToken) : Task.FromResult( false );
本文来自电脑杂谈,转载请注明本文网址:
https://www.pc-fly.com/a/jisuanjixue/article-60185-3.html
留言好多托
好多台湾人搞不懂