RubenHerman
RubenHerman

Reputation: 1854

SimpleInjector Singleton LifeStyle in Web

Let's say I have an IOC container. I use that container to register a logger with a singleton lifestyle:

var container = new Container();
container.Register<ILogger, Logger>(LifeStyle.Singleton);

Now when I use this singleton, there will only be one instance created for it. But my question is, for example for an ASP.NET web. Is that the same instance that is used through the whole application for that one user or for EVERY user going to my website?

What if it's for every user and the logger is busy logging something and another user also tries to log something? Will that throw an error? (what I mean... what is the best practice for a logger?)

Upvotes: 3

Views: 2842

Answers (1)

Steven
Steven

Reputation: 172606

The Simple Injector documentation states:

There will be at most one instance of the registered service type and the container will hold on to that instance until the container is disposed or goes out of scope. Clients will always receive that same instance from the container. [...] Simple Injector guarantees that there is at most one instance of the registered Singleton inside that Container instance, but if multiple Container instances are created, each Container instance will get its own instance of the registered Singleton.

Another part of the documentation describes that:

You should typically create a single Container instance for the whole application (one instance per app domain); Container instances are thread-safe.

This means that since you will typically create just one container instance, Singleton registrations will have only one instance for the complete AppDomain. So every user and every request will use that same instance.

It is your responsibility to make sure that such implementation is thread-safe and can be used by multiple threads in parallel.

In case you can't guarantee thread-safety, such instance should be registered as Scoped or Transient.

You should consult the documentation of the used logging library to find out whether instances of the type are thread-safe or not.

Instead of injecting a 3rd party library abstraction in your code, do consider the alternative design described here.

Upvotes: 4

Related Questions