Unity is a lazy decision

I have an application MVC

webApi

that works with Unity

. I have to allow interface ITest

for singleton class ( DelegateHandler

). But the ITest interface has a httprequest

lifelong manager, and that's important. So I cannot resolve ITest on the event Application_Start

because there is no HttpRequest right now, but the DelegateHandler will only use ITest in the httprequest lifecycle.

So is it possible to post a lazy DelegateHandler solution, or maybe someone else has an interesting solution?

+3


source to share


2 answers


The lifetime of a service should always be equal to or shorter than that of its dependencies, so you usually log it ITest

as an Http or Transient request, but if that is not possible, wrap a dependency ( DelegateHandler

I assume) that has an 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 }));

      

+2


source


Another option is to do the following:

public class Foo
{
    Func<IEnumerable<ITest>> _resolutionFunc;
    ITest _test;
    public Foo(Func<IEnumerable<ITest>> resolutionFunc)
    {
        _resolutionFunc=resolutionFunc;
    }

private void ResolveFuncToInstance()
{
    _test=_resolutionFunc().First();
}
}

      



What we do is ask Unity to provide us with a delegate that will resolve all ITest instances in the container. Since it's Func, we can call it whenever we want to make a real resolution from Unity.

This does the same thing Stephen does, but uses Unity's built-in functionality to do what we're looking for.

0


source







All Articles