Lifestyle.CreateCustom Method
Creates a custom lifestyle using the supplied lifestyleApplierFactory delegate.
Namespace:
SimpleInjector
Assembly:
SimpleInjector (in SimpleInjector.dll) Version: 5.3.0
public static Lifestyle CreateCustom( string name, CreateLifestyleApplier lifestyleApplierFactory )
Parameters
- name
- Type: SystemString
The name of the lifestyle to create. The name is used to display the lifestyle in the debugger. - lifestyleApplierFactory
- Type: SimpleInjectorCreateLifestyleApplier
A factory delegate that takes a Func<object> delegate that will produce a transient instance and returns a delegate that returns cached instances.
Return Value
Type: Lifestyle
A new Lifestyle.
The supplied lifestyleApplierFactory will be called just once per registered service. The supplied lifestyleApplierFactory will be called by the framework when the type is resolved for the first time, and the framework will supply the factory with a Func<object> for creating new (transient) instances of that type (that might have been intercepted and initializers might have been applied). It is the job of the lifestyleApplierFactory to return a Func<object> that applies the proper caching. The Func<object> that is returned by the lifestyleApplierFactory will be stored for that registration (every registration will store its own Func<object> delegate) and this delegate will be called every time the service is resolved (by calling
container.GetInstance<TService>
or when that service is injected into another type).
The following example shows the creation of a lifestyle that caches registered instances for 10 minutes:
var customLifestyle = Lifestyle.CreateCustom("Absolute 10 Minute Expiration", instanceCreator => { TimeSpan timeout = TimeSpan.FromMinutes(10); var syncRoot = new object(); var expirationTime = DateTime.MinValue; object instance = null; return () => { lock (syncRoot) { if (expirationTime < DateTime.UtcNow) { instance = instanceCreator(); expirationTime = DateTime.UtcNow.Add(timeout); } return instance; } }; }); var container = new Container(); container.Register<IService, MyService>(customLifestyle); container.Register<AnotherService, MeTwoService>(customLifestyle);