Denis Agarev
Denis Agarev

Reputation: 1529

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?

Upvotes: 3

Views: 1031

Answers (2)

Faster Solutions
Faster Solutions

Reputation: 7005

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're doing is asking Unity to provide us with a delegate that will resolve all ITest instances in the container. As this is a Func we can call it whenever we want to do the actual resolution from Unity.

This does much the same thing as Steven is doing, but uses inbuilt Unity functionality to do what we're looking for.

Upvotes: 0

Steven
Steven

Reputation: 172666

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 }));

Upvotes: 2

Related Questions