Join GitHub today
Add Stateless / Automatic / Dynamic lifestyle #608
Most registered components will, by themselves, contain no state, except the state implicitly 'inherited' from their dependencies.
This means that this component can get the same lifestyle as the shortest lifestyle of its dependencies. In case there are no dependencies, the component can become a singleton. In other words, their lifestyle can be implied an inherited from the dependencies.
Registering components with an 'automatic' lifestyle can optimize performance and reduce changes from being made when dependencies are introduced. When a scoped leaf dependency is introduced, it will cascade up through its consumers that will have their lifestyle 'lowered'.
To prevent this cascading, making object graphs transient is the simplest solution, but much less performant.
By letting Simple Injector know that "this component is stateless", Simple Injector can do the math for you.
var container = new Container(); container.Options.DefaultLifestyle = Lifestyle.Automatic; container.Register<HomeController>(Lifestyle.Transient); container.Register<CommerceContext>(Lifestyle.Scoped); // uses 'auto' lifestyle container.Register<IUserContext, AspUserContext>();
This sounds sophisticated. I like the idea very much, for advanced users....
I see however also some downsides. In order of coming to my mind:
So to use this feature, you'll have to do an exam. Passing the exam gives you the lazy bastard lifestyle, failing the test... well we have to think about that one.
Occasionally stumbled on this one, let me add my two cents.
I surely do agree that automatic lifestyle should not be the default one, since it might break some things.