Lazy Unity

advertisements

I have MVC webApi application which works with Unity. I have to resolve interface ITest to singleton class (DelegateHandler). But interface ITest has per httprequest lifetime manager and it is important. So i can't resolve ITest on Application_Start event because there isn't HttpRequest right now but DelegateHandler will use ITest only in httprequest life cycle.

So is it possible to send lazy resolve to DelegateHandler or maybe somebody have other interesting solution?


The lifetime of a service should always be equal or shorter than that of its dependencies, so you would typically register ITest as Per Http Request or Transient, but if that's not possible, wrap the dependency (DelegateHandler I assume) that has a per Http Request lifetime in a proxy:

// Proxy
public class DelegateHandlerProxy : IDelegateHandler
{
    public Container Container { get; set; }

    // IDelegateHandler implementation
    void IDelegateHandler.Handle()
    {
        // Forward to the real thing by resolving it on each call.
        this.Container.Resolve<RealDelegateHandler>().Handle();
    }
}

// Registration
container.Register<IDelegateHandler>(new InjectionFactory(
    c => new DelegateHandlerProxy { Container = c }));