如何在简单的注入器中注册<Func<Type, IEnumerable<T>>
How to Register<Func<Type, IEnumerable<T>> in simple injector
我正在尝试在我的系统中实现 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" });
如果您的处理程序是泛型,您可以尝试使用以下逻辑添加它们,首先使用 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);
我正在尝试在我的系统中实现 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" });
如果您的处理程序是泛型,您可以尝试使用以下逻辑添加它们,首先使用 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);