Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity lazy resolve

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?

like image 937
Denis Agarev Avatar asked Mar 22 '26 19:03

Denis Agarev


1 Answers

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 }));
like image 62
Steven Avatar answered Mar 25 '26 10:03

Steven



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!