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

我正在使用带有EF Core 2.0的ASP.NET Core 2.0构建应用程序.至于在我的域中解耦不同种类的逻辑,我使用DDD(域驱动设计)的域事件.让我们深入研究实现,看看有什么,然后我将讨论我的问题.
首先,让我们看一下与域事件相关的类的通用实现.首先是标记接口IDomainEvent:

public interface IDomainEvent
{
}

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

public interface IHandler<in T> where T : IDomainEvent
{
    void Handle(T domainEvent);
}

然后,我有一个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());
}

如您所见,DomainEvents类将初始化执行程序集的所有域事件.在域的自定义DbContext的重写SaveChanges()方法中调用Dispatch方法.我在此调用调度,以便在工作单元的事务处调度所有事件:

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

    return base.SaveChanges();
}

并执行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);
        }
    }

到目前为止,它可以与简单的域事件处理程序很好地协同工作,例如:

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

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

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));
    }
}

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

System.MissingMethodException: 'No parameterless constructor defined for this object.'

这是合乎逻辑的,因为在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();
    }

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

解决方法:

解决方案是使用依赖注入容器创建具有依赖关系的对象的实例.为此,您需要将IContainer向下传递到DomainEvents实例,即作为参数传递给DomainEvents.Init()方法调用.

    // 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 container = CreateIoCContainer(services);
        var autofacServiceProvider = new AutofacServiceProvider(container);
        DomainEvents.Init(container);

        return autofacServiceProvider;
    }

然后,DomainEvents类应该存储对该容器的引用,并在Dispatch方法中使用它.

注意1:我没有使用C#的丰富经验,所以我不确定是否应该将IContainer或IServiceProvider注入DomainEvents.

注意2:正如@TSeng在评论中所说,请尽量不要使用静态方法;重构为使用类的实例.

上一篇:c#-Autofac模块应该注册自己的从属模块吗?


下一篇:如何用云存储和CDN加速网站图片视频、阿里云OSS的使用(转)