C# 使用动态构造的事件处理程序处理 DDD 域事件

mir*_*nd4 5 c# domain-driven-design autofac asp.net-core

我正在使用 ASP.NET Core 2.0 和 EF Core 2.0 构建一个应用程序。至于解耦我的领域中的不同类型的逻辑,我使用DDD(领域驱动设计)的领域事件。让我们深入了解实施情况,看看我有什么,然后我将讨论我的问题。首先,让我们看看我的领域事件相关类的通用实现。首先是标记界面IDomainEvent

public interface IDomainEvent
{
}
Run Code Online (Sandbox Code Playgroud)

在它旁边我有一个通用IHandler类:

public interface IHandler<in T> where T : IDomainEvent
{
    void Handle(T domainEvent);
}
Run Code Online (Sandbox Code Playgroud)

然后我有一DomainEvents堂课:

private static List<Type> _handlers;

public static void Init()
{
    InitHandlersFromAssembly();
}

private static void InitHandlersFromAssembly()
{
    _handlers = Assembly.GetExecutingAssembly()
        .GetTypes()
        .Where(x => x.GetInterfaces().Any(y => y.IsGenericType && y.GetGenericTypeDefinition() == typeof(IHandler<>)))
        .ToList();
}

public static void Dispatch(IDomainEvent domainEvent)
{
    foreach (var handlerType in _handlers)
    {
        if (CanHandleEvent(handlerType, domainEvent))
        {
            dynamic handler = Activator.CreateInstance(handlerType);
            handler.Handle((dynamic)domainEvent);
        }
    }
}

private static bool CanHandleEvent(Type handlerType, IDomainEvent domainEvent)
{
    return handlerType.GetInterfaces()
        .Any(x => x.IsGenericType
                  && x.GetGenericTypeDefinition() == typeof(IHandler<>)
                  && x.GenericTypeArguments[0] == domainEvent.GetType());
}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,该类DomainEvents初始化了执行程序集的所有域事件。该方法是在我的域自定义的Dispatch重写方法中调用的。我在这里调用调度是为了调度工作单元事务中的所有事件:SaveChanges()DbContext

public override int SaveChanges()
{
    DomainEventsDispatcher.Dispatch(ChangeTracker);

    return base.SaveChanges();
}
Run Code Online (Sandbox Code Playgroud)

并实施DomainEventDispatcher

public static class DomainEventsDispatcher
{
    public static void Dispatch(ChangeTracker changeTracker)
    {
        var domainEvents = GetDomainEventEntities(changeTracker);

        HandleDomainEvents(domainEvents);
    }

    private static IEnumerable<IEntity> GetDomainEventEntities(ChangeTracker changeTracker)
    {
        return changeTracker.Entries<IEntity>()
            .Select(po => po.Entity)
            .Where(po => po.Events.Any())
            .ToArray();
    }

    private static void HandleDomainEvents(IEnumerable<IEntity> domainEventEntities)
    {
        foreach (var entity in domainEventEntities)
        {
            var events = entity.Events.ToArray();
            entity.Events.Clear();

            DispatchDomainEvents(events);
        }
    }

    private static void DispatchDomainEvents(IDomainEvent[] events)
    {
        foreach (var domainEvent in events)
        {
            DomainEvents.Dispatch(domainEvent);
        }
    }
Run Code Online (Sandbox Code Playgroud)

到目前为止一切顺利,它与简单的域事件处理程序配合得很好,例如:

public class OrderCreatedEventHandler : IHandler<OrderCreatedEvent>
{
    public void Handle(OrderCreatedEvent domainEvent)
    {
        Console.WriteLine("Order is created!");
    }
}
Run Code Online (Sandbox Code Playgroud)

但我还有一些其他事件处理程序,我想在其中注入一些依赖项,即存储库:

public class OrderCreatedEventHandler : IHandler<OrderCreatedEvent>
{
    private readonly IOrderHistoryRepository _orderHistoryRepository;

    public OrderCreatedEventHandler(IOrderHistoryRepository orderHistoryRepository)
    {
        _orderHistoryRepository = orderHistoryRepository;
    }

    public void Handle(OrderCreatedEvent domainEvent)
    {
        _orderHistoryRepository.Insert(new OrderHistoryLine(domainEvent));
    }
}
Run Code Online (Sandbox Code Playgroud)

我的问题如下:在DomainEventsDispatch方法中,我使用Activator类在运行时动态构造事件处理程序。在这一行,抛出异常并显示以下消息:

System.MissingMethodException: 'No parameterless constructor defined for this object.'
Run Code Online (Sandbox Code Playgroud)

这是合乎逻辑的,因为只有OrderCreatedEventHandler一个构造函数注入了存储库。我的问题是:是否可以将该存储库注入到我的动态构建的处理程序中?如果不是,我的问题的解决方案或解决方法是什么?

附加信息:

作为 IoC 框架,我使用 Autofac,并将其配置在Startup.cs域事件也初始化的位置:

    // This method gets called by the runtime. Use this method to add services to the container.
    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        services.AddMokaKukaTrackerDbContext(CurrentEnvironment, Configuration);
        services.RegisterIdentityFramework();
        services.AddAndConfigureMvc(CurrentEnvironment);

        var autofacServiceProvider = new AutofacServiceProvider(CreateIoCContainer(services));
        DomainEvents.Init();

        return autofacServiceProvider;
    }

    private static IContainer CreateIoCContainer(IServiceCollection services)
    {
        var builder = new ContainerBuilder();
        builder.Populate(services);
        builder.RegisterModule(new AutofacInjectorBootstrapperModule());

        return builder.Build();
    }
Run Code Online (Sandbox Code Playgroud)

如果您需要有关我的问题的更多信息/代码,请告诉我,然后我会尽快将其包含在内。提前致谢!

小智 5

我决定按照 @Devesh Tipe 的要求提出问题的最终解决方案。已批准的解决方案解决了我的问题,但我在代码库中进行了多次重构,以便以更优雅的方式处理域事件。通过以下解决方案,我们能够创建具有依赖项的域处理程序,这些依赖项在运行时通过 Autofac 依赖项框架进行解析。让我们深入研究代码,包括整个解决方案:

首先,我有一个领域事件的标记接口:

public interface IDomainEvent
{
}
Run Code Online (Sandbox Code Playgroud)

然后我有一个用于域处理程序的接口:

public interface IHandler<in T> where T : IDomainEvent
{
    void Handle(T domainEvent);
}
Run Code Online (Sandbox Code Playgroud)

此外,我有一个EventDispatcher负责调度/处理一个事件的:

public class EventDispatcher : IEventDispatcher
{
    private readonly ILifetimeScope _lifetimeScope;

    public EventDispatcher(ILifetimeScope lifetimeScope)
    {
        _lifetimeScope = lifetimeScope;
    }

    public void Dispatch<TEvent>(TEvent eventToDispatch) where TEvent : IDomainEvent
    {
        foreach (dynamic handler in GetHandlers(eventToDispatch))
        {
            handler.Handle((dynamic)eventToDispatch);
        }
    }

    private IEnumerable GetHandlers<TEvent>(TEvent eventToDispatch) where TEvent : IDomainEvent
    {
        return (IEnumerable) _lifetimeScope.Resolve(
            typeof(IEnumerable<>).MakeGenericType(
                typeof(IHandler<>).MakeGenericType(eventToDispatch.GetType())));
    }
}
Run Code Online (Sandbox Code Playgroud)

如您所见,此处将检索并调用相应的处理程序及其已解析的依赖项。该调度程序在执行程序类中使用,例如:

public class DomainEventHandlingsExecutor : IDomainEventHandlingsExecutor
{
    private readonly IEventDispatcher _domainEventDispatcher;

    public DomainEventHandlingsExecutor(IEventDispatcher domainEventDispatcher)
    {
        _domainEventDispatcher = domainEventDispatcher;
    }

    public void Execute(IEnumerable<IEntity> domainEventEntities)
    {
        foreach (var entity in domainEventEntities)
        {
            var events = entity.Events.ToArray();
            entity.Events.Clear();

            foreach (var @event in events)
            {
                _domainEventDispatcher.Dispatch(@event);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

哪个被注入到我的数据库上下文中:

    public MokaKukaTrackerDbContext(DbContextOptions<MokaKukaTrackerDbContext> options, IDomainEventHandlingsExecutor domainEventHandlingsExecutor) : base(options)
    {
        _domainEventHandlingsExecutor = domainEventHandlingsExecutor;
    }

    public override int SaveChanges()
    {
        var numberOfChanges = base.SaveChanges();

        _domainEventHandlingsExecutor.Execute(GetDomainEventEntities());

        return numberOfChanges;
    }

    private IEnumerable<IEntity> GetDomainEventEntities()
    {
        return ChangeTracker.Entries<IEntity>()
            .Select(po => po.Entity)
            .Where(po => po.Events.Any())
            .ToArray();
    }
Run Code Online (Sandbox Code Playgroud)

最后但并非最不重要的一点是,我AutofacModule注册了与域事件处理相关的所有处理程序和逻辑:

public class AutofacEventHandlingBootstrapperModule : Module
{
    protected override void Load(ContainerBuilder builder)
    {
        builder.RegisterType<EventDispatcher>().As<IEventDispatcher>().InstancePerLifetimeScope();
        builder.RegisterType<DomainEventHandlingsExecutor>().As<IDomainEventHandlingsExecutor>().InstancePerLifetimeScope();

        RegisterEventHandlersFromDomainModel(builder);
    }

    private static void RegisterEventHandlersFromDomainModel(ContainerBuilder builder)
    {
        var domainModelExecutingAssembly = new DomainModelExecutingAssemblyGetter().Get();

        builder.RegisterAssemblyTypes(domainModelExecutingAssembly)
            .Where(t => t.GetInterfaces().Any(i => i.IsClosedTypeOf(typeof(IHandler<>))))
            .AsImplementedInterfaces()
            .InstancePerLifetimeScope();
    }
}
Run Code Online (Sandbox Code Playgroud)

当然必须在以下位置注册Startup.cs

   public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        services.AddMokaKukaTrackerDbContext(CurrentEnvironment, Configuration);

        return new AutofacServiceProvider(CreateIoCContainer(services));
    }

    private static IContainer CreateIoCContainer(IServiceCollection services)
    {
        var builder = new ContainerBuilder();
        builder.Populate(services);
        builder.RegisterModule(new AutofacInjectorBootstrapperModule());
        builder.RegisterModule(new AutofacEventHandlingBootstrapperModule());

        return builder.Build();
    }
Run Code Online (Sandbox Code Playgroud)

就是这样,我希望它对某人有帮助!