我正在使用带有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
类初始化正在执行的程序集的所有域事件。在我的自定义Dispatch
域的覆盖SaveChanges()
方法中调用DbContext
方法。我在这里调用调度,以便在一个工作单元的交易中发送所有事件:
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();
}
如果您需要有关我的问题的更多信息/代码,请告诉我,然后我会尽快加入。提前谢谢!
答案 0 :(得分:2)
解决方案是使用依赖注入容器来创建具有依赖关系的对象的实例。为此,您需要将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
类应存储对container
的引用,并在Dispatch
方法中使用它。
注1:我没有很多C#的经验,所以我不确定是否应该注入IContainer
或IServiceProvider
DomainEvents
注2:正如@TSeng在评论中所说,尽量不要使用静态方法;重构使用类的实例。
答案 1 :(得分:2)
我决定为@Devesh Tipe提出问题的最终解决方案。批准的解决方案解决了我的问题,但我在我的代码库中做了几次重构,以便以更优雅的方式处理域事件。通过以下解决方案,我们可以创建具有依赖关系的域处理程序,这些依赖关系在运行时通过Autofac依赖关系框架解析。让我们深入研究代码,包括整个解决方案:
首先,我有一个域事件的标记界面:
public interface IDomainEvent
{
}
然后我有一个域处理程序接口:
public interface IHandler<in T> where T : IDomainEvent
{
void Handle(T domainEvent);
}
此外,我有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())));
}
}
如您所见,此处检索并调用具有已解析依赖项的相应处理程序。此调度程序用于执行程序类,如:
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);
}
}
}
}
注入我的db上下文:
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();
}
最后但并非最不重要的是,我在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();
}
}
当然必须在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();
}
那就是它,我希望它对某人有帮助!