LifestyleCreateCustom Method

Simple Injector
Creates a custom lifestyle using the supplied lifestyleApplierFactory delegate.

Namespace:  SimpleInjector
Assembly:  SimpleInjector (in SimpleInjector.dll) Version: 4.0.0
Syntax

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.
Exceptions

ExceptionCondition
ArgumentNullExceptionThrown when one of the arguments is a null reference (Nothing in VB).
ArgumentExceptionThrown when name is an empty string.
Remarks

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).
Examples

The following example shows the creation of a lifestyle that caches registered instances for 10 minutes:
C#
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;

    // If the application has multiple registrations using this lifestyle, each registration
    // will get its own Func<object> delegate (created here) and therefore get its own set
    // of variables as defined above.
    return () =>
    {
        lock (syncRoot)
        {
            if (expirationTime < DateTime.UtcNow)
            {
                instance = instanceCreator();
                expirationTime = DateTime.UtcNow.Add(timeout);
            }

            return instance;
        }
    };
});

var container = new Container();

// We can reuse the created lifestyle for multiple registrations.
container.Register<IService, MyService>(customLifestyle);
container.Register<AnotherService, MeTwoService>(customLifestyle);
See Also

Reference