I have a requirement were I need some instances of my domain to remain the same during a scope of my choosing. These instances are an exception and the norm should be that all instances are new each time they are requested by the domain. (The way transient life time should work)
Problem is I cant find a DI Container that works this way.
I have tested Castle Windsor and StructureMap.
In StructureMap you do
using(var nested = container.GetNestedContainer())
{
var whatEver = nested.GetInstance<IWhatEver>();
}
The default will now be that the instances live during the entire life of the nested container. If you want the behavior I want you need to register all types that should be truly transient like
config
.For<IMyTransientType>()
.LifecycleIs(new UniquePerRequestLifecycle())
.Use<MyTransientType>();
This will not work, I want the default behavior to be the other way around. So do you guys know a IoC that work this way, or that can be configured so that default behavior is like this.
edit: For the curious you can check out this working branch here using Structure map, https://github.com/AndersMalmgren/FreePIE/blob/MoveToStructureMap/FreePIE.Core/Common/StructureMap/StructureMapScopedContext.cs. You can anywere in the domain create a scoped life time using the interface IScopedContext<TEntryPoint>
. Problem is that it defualts to "scoped" lifetime instead of transient life time. To get real transient life time you need set it to always unique. I have solved it for unregister concrete types with this little hacky helper
From the DI bootstrapper I then do
var assebmlies = container
.GetInstance<IPluginDataSource>()
.ListAllPluginTypes()
.GroupBy(t => t.Assembly)
.Select(g => g.Key);
assebmlies.ForEach(a => container.Configure(config => config.Scan(scan =>
{
scan.Assembly(a);
scan.Convention<ConcreteTypeRegistrationConvention>();
})));