|> but what about the instances of IEventListener (EmailNotifier and SMSNotifier) provided by the enumerator? Will they be singleton? or their life cycle is managed separately (e.g WebApiRequestLifestyle)?
Simple Injector works a bit differently in some cases than the other DI libraries do. Most libraries will inject an array or list into your class any time you expose an IEnumerable<T>. That means that every inject a new array has to be created in memory.
Simple Injector takes a different approach. The injected 'collection' is really
an enumerator. It produces new instances every time you iterate it. So you can see it as a factory and it will spit out instances based on their lifestyle. Take the following
example for instance:
var mailNotifier1 = container.GetAllInstances<IEventListener>().First();
var mailNotifier2 = container.GetAllInstances<IEventListener>().First();
var smsNotifier1 = container.GetAllInstances<IEventListener>().Last();
var smsNotifier2 = container.GetAllInstances<IEventListener>().Last();
In the previous example
is registered as Singleton, while
is registered as transient. Simple Injector will obey the lifestyle registrations of the registered instances. This means that no matter how many time the first element (the EmailNotifier) is requested from the collection, you are guaranteed
to get the same instance. Since the
however is registered as transient, every time you iterate the enumerable, you will get a new instance.
Not only does this work with Singleton and Transient, this works for every lifestyle you specify.