【发布时间】:2015-06-03 16:10:22
【问题描述】:
我正在尝试使用 Simple Injector 在 C# 中实现域事件模式。
我已将我的代码简化为一个可以作为控制台应用程序运行的文件,并排除了 Simple Injector 代码以保持问题清晰。
我遇到的问题是每个事件可能有多个事件处理程序,并且可能引发多个事件,但我想限制我的 Dispatcher 只处理实现 IEvent 接口的事件,所以我把这个限制放在我的调度方式。
这导致了如何从 Simple Injector 获取实例的问题,因为每次调用 Dispatch 方法时,TEvent 的类型为 IEvent(正如我所料),但我需要获取传入的事件,因此我可以从 Simple Injector 获取相关的处理程序。
希望我的代码能更好地解释这一点:
interface IEvent
{
}
interface IEventHandler<T> where T : IEvent
{
void Handle(T @event);
}
class StandardEvent : IEvent
{
}
class AnotherEvent : IEvent
{
}
class StandardEventHandler : IEventHandler<StandardEvent>
{
public void Handle(StandardEvent @event)
{
Console.WriteLine("StandardEvent handled");
}
}
class AnotherEventHandler : IEventHandler<AnotherEvent>
{
public void Handle(AnotherEvent @event)
{
Console.WriteLine("AnotherEvent handled");
}
}
这是我的调度员:
static class Dispatcher
{
// I need to get the type of @event here so I can get the registered instance from the
// IoC container (SimpleInjector), however TEvent is of type IEvent (as expected).
// What I need to do here is Get the registered instance from Simple Injector for each
// Event Type i.e. Container.GetAllInstances<IEventHandler<StandardEvent>>()
// and Container.GetAllInstances<IEventHandler<AnotherEvent>>()
public static void Dispatch<TEvent>(TEvent @event) where TEvent : IEvent
{
}
}
class PlainOldObject
{
public ICollection<IEvent> Events = new List<IEvent>
{
new StandardEvent(),
new AnotherEvent()
};
}
class StandAlone
{
static void Main(string[] args)
{
var poco = new PlainOldObject();
foreach (var @event in poco.Events)
{
Dispatcher.Dispatch(@event);
}
}
}
我已经在 Dispatch 方法中评论了我的问题。有人知道我应该如何解决这个问题吗?
问候, 加里
【问题讨论】:
标签: c# generics inversion-of-control simple-injector