3

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?

2 Answers 2

2

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 }));
Sign up to request clarification or add additional context in comments.

1 Comment

Would be cool to convert it generic solution but propably it's impossible)
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.