Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IoC container mappings: singleton vs each-call creation

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>();
like image 566
Dzmitry Martavoi Avatar asked Dec 10 '15 13:12

Dzmitry Martavoi


1 Answers

Object lifetime management using DI container usually boils down to:

  1. Singleton scoped (sometimes container scoped)
  2. Transient (per request from container)
  3. Per graph(context) (example: presenter/controller in desktop applications, session in web applications/web servers)

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.

like image 117
Cortlendt Avatar answered Nov 04 '22 15:11

Cortlendt