Autofac: Check if instance is already resolved

asp.net-web-api, autofac, c#

Solution

First, create a class that can track whether the instance is resolved or not:

public class Tracker
{
    public bool IsResolved { get; set; }
}

(You may wish to pretty this up a bit :))

Register it with the same scope as whatever you want to track:

builder.RegisterType<Tracker>()
    .InstancePerHttpRequest();

Then, in the `OnActivated` event, set the bool:

builder.Register((c, p) => {
        return new MyClass();
    })
    .As<IMyClass>()
    .InstancePerHttpRequest()
    .OnActivated(e => {
        e.Context.Resolve<Tracker>().IsResolved = true;
    });

You could also set the field during activation (in the first delegate) but using the `OnActivated` event makes it easier to generalise this if you want to.

Finally, to check the field:

if (container.Resolve<Tracker>().IsResolved) { ... }

Problem

I do this: https://stackoverflow.com/questions/12069002/autofac-resolve-with-and-without-named-parameter I register an interface. For the initialization a parameter is needed. A first call will pass this parameter. On another place i want to resolve this instance of the interface too, but i don't can pass this parameter. Is it possible to check if this interface was already resolved (in the current scope. I use the ASP.NET WEB API)? If i resolve it without the parameter, I get an exception. I need to check if in the current HttpRequest-scope the is already resolved (so I can get it without passing the parameter, because if it is already resolved, the registered creation-delegate will not be called twice) ``` m_builder.Register<IMyClass((c, p) => { //... return new MyClass; }).InstancePerHttpRequest();//.InstancePerApiRequest(); ```

Original source