我如何使用 Simple Injector 注入 IEnumerable>?
简要介绍一下,我正试图创建所有 EventHandlers ,这些处理程序知道如何处理一个特定的事件。这是我的容器注册代码:
所以当我调用Simple Injector时:
我会得到一个 `IEnumerable>`。
对于只有一个实现的接口,可以使用以下方式进行注册:
在注册的末尾添加以下ResolveUnregisteredType:
简要介绍一下,我正试图创建所有 EventHandlers ,这些处理程序知道如何处理一个特定的事件。这是我的容器注册代码:
container.RegisterCollection(typeof(IHandleDomainEvent<>),
AppDomain.CurrentDomain.GetAssemblies());
以下是两个实现相同事件的 IHandleEvent<T>
接口的类:
public class Reservation : IHandleDomainEvent<OrderConfirmed>{}
public class Order: IHandleDomainEvent<OrderConfirmed>{}
所以当我调用Simple Injector时:
var handlers = _container.GetAllInstances<Func<IHandleDomainEvent<OrderConfirmed>>>();
我希望能够收到 IEnumerable<Func<IHandleDomainEvent<OrderConfirmed>>>
只是为了澄清,我知道如果我调用:
var handlers = _container.GetAllInstances<IHandleDomainEvent<OrderConfirmed>>();
我会得到一个 `IEnumerable>`。
对于只有一个实现的接口,可以使用以下方式进行注册:
container.Register(typeof(IHandleDomainEvent<>),
AppDomain.CurrentDomain.GetAssemblies(), Lifestyle.Scoped);
在注册的末尾添加以下ResolveUnregisteredType:
container.ResolveUnregisteredType += (o, args) => ResolveFuncOfT(o, args, container);
// Function
private static void ResolveFuncOfT(object s, UnregisteredTypeEventArgs e, Container container)
{
var type = e.UnregisteredServiceType;
if (!type.IsGenericType || type.GetGenericTypeDefinition() != typeof(Func<>)) return;
Type serviceType = type.GetGenericArguments().First();
InstanceProducer producer = container.GetRegistration(serviceType, true);
Type funcType = typeof(Func<>).MakeGenericType(serviceType);
var factoryDelegate = Expression.Lambda(funcType, producer.BuildExpression()).Compile();
e.Register(Expression.Constant(factoryDelegate));
}
将允许调用:
var handler = _container.GetInstance<Func<IHandleDomainEvent<TEvent>>>();