我正在尝试在系统中实现cqrs,如何在简单的注入器中注册泛型集合?当我尝试运行代码时,遇到异常,请使用其他重载之一注册此类型。
public class Ioc
{
public static SimpleInjector.Container Container;
static Ioc()
{
Container = new SimpleInjector.Container();
Container.Register<IHandleEvent, Handler>(Lifestyle.Transient);
Container.Register<ICommandsBus, CommandsBus(Lifestyle.Transient);
Container.Register<IEventsBus, EventsBus>(Lifestyle.Transient);
Container.Register<Func<Type, IEnumerable<IHandleEvent>>> (Lifestyle.Transient);
}
}
//Without any Conatiner working
List<Handler> handlers = new List<Handler>();
Handler handler = new Handler();
handlers.Add(handler);
Func<Type, IEnumerable<IHandleEvent>> func = f => handlers;
EventsBus eventsBus = new EventsBus(func);
eventsBus.Publish(new User { Id = 1, Login = "Test" });
// I want something like this
var bus = Ioc.Container.GetInstance<IEventsBus>();
bus.Publish(new User { Id = 1, Login = "tt" });
答案 0 :(得分:0)
如果处理程序是泛型的,则可以尝试使用以下逻辑添加它们,首先使用GetTypesToRegister获取它们,然后注册为集合
// assemblies - assemblies with your handlers
var notificationHandlerTypes =
Container.GetTypesToRegister(typeof(IHandleEvent<>), assemblies, new
TypesToRegisterOptions
{
IncludeGenericTypeDefinitions = true,
IncludeComposites = false,
});
Container.Collection.Register(typeof(IHandleEvent<>), notificationHandlerTypes);