Lets assume we have a very simple IConfiguration interface that responsible for returning a proper connection string
interface IConfiguration
{
string ConnectionString {get;}
}
and lets assume only one instance of type that implemented such interface can be used (because it just returns a string, not manage a state, etc.)
So, there are, at least, two ways of how the interface could be registered within a container: as usual - new object per each type requesting, or as a singleton - one object for all type requests. Are there any differences between approaches (maybe performance reasons, lifetime management tricks, etc.)
container.For<IConfiguration>().Use<ConfigurationImpl>();
vs
container.For<IConfiguration>().Singleton().Use<ConfigurationImpl>();
Object lifetime management using DI container usually boils down to:
I urge you to read Mark Seemanns excelent book Dependency Injection in .Net. It has special chapter dedicated to object lifetime management.
In general you're thread-safe with transients and singleton is good for performance reasons or state sharing. You also must make careful note of how your resources are being disposed.
If you have a framework the implies some design you can use parts of this framework as a context for lifetime of the instance.
Example: you have 2 dbcommands used by asp mvc controller so you can share dbsession between them by making dbsession lifetime tied to the controller lifetime.
There are more ways to manage object lifetime - like pooled, lazy loaded or futures, but they're quite less used than the first 3. Read on Mark Seemann for that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With