简单注入器注入IEnumerable <func <t>&gt;

时间:2018-04-09 16:34:15

标签: c# dependency-injection expression-trees simple-injector

如何使用Simple Injector注入IEnumerable<Func<T>>

只是为了添加一些上下文,我试图创建所有知道如何处理一个特定事件的EventHandler。所以这是我的Container注册:

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<IHandleDomainEvent<OrderConfirmed>>

对于只有一个实现的接口,使用以下命令进行注册:

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>>>();

1 个答案:

答案 0 :(得分:4)

这是Simple Injector的美妙之处:您永远不必解析IEnumerable<Func<T>>,因为Simple Injector解析的任何IEnumerable<T>已经充当

这意味着当您解析IEnumerable<T>时,将解析流的元素 none 。它们仅在迭代可枚举时得到解决,并逐个解析。

在迭代流时,元素将根据其生活方式得到解决。这意味着当集合中的元素为Transient时,对流进行两次迭代将导致创建新的瞬态实例。

示例:

// Only resolves the enumerable, not the contained handlers.
// This enumerable itself is a singleton, you can reference it forever.
var collection = container.GetInstances<IEventHandler<OrderConfirmed>>();

// Calls back into the container to get the first element, but nothing more
var first = collection.First();

// Since the stream that Simple Injector returns is a IList<T>, getting the last
// element is an O(1) operation, meaning that only the last element is resolved;
// not the complete collection.
var last = collection.Last();

// Calling .ToArray(), however, will obviously resolve all registrations that are 
// part of the collection.
var all = collection.ToArray();

// Iterating a stream will always call back into the container, which ensures
// that the stream adheres to the elements lifestyles. Transients will be
// created on each iteration, while singletons will only be created once.
container.Register<Apple>(Lifestyle.Transient);
container.Register<Banana>(Lifestyle.Singleton);
container.RegisterCollection<IFruit>(typeof(Apple), typeof(Banana));
var fruits = container.GetAllInstances<IFruit>();
Assert.AreNotSame(fruits.First(), fruits.First());
Assert.AreSame(fruits.Last(), fruits.Last());

// Even other collection types such as IReadOnlyCollection<T> behave as streams
var col = container.GetInstance<IReadOnlyCollection<IEventHandler<OrderConfirmed>>();

// This gives you the possibility to get a particular item by its index.
var indexedItem = col[3];

您可以在此处找到有关在Simple Injector中使用集合的更多信息: