Per Thread Lifetime
Per thread lifetime means a new instance of the registered Type will be created once per each thread. In other words, if a Resolve<T>()
method is called on a thread the first time, it will return a new object. Each subsequent call to Resolve<T>()
, or when the dependency mechanism injects instances of the type into other classes on the same thread, the container will return the same object.
The Lifetime Manager
Per thread lifetime is controlled by PerThreadLifetimeManager type. This lifetime manager effectively implements a singleton behavior for objects on a per-thread basis.
Registration
Per thread lifetime is only supported by Type and Factory registrations. Instance registration does not support this lifetime.
Example
To create a Type registration with per thread lifetime:
container.RegisterType<IService, Service>(TypeLifetime.PerThread);
or you could register a factory:
container.RegisterFactory<IService>((c, t, n) => new Service(),
FactoryLifetime.PerThread);
Note
Please note that registrations use TypeLifetime and FactoryLifetime respectively.