Search code examples
c#asp.net-web-apiautofac

Registering the container itself with Autofac does not work in ASP.NET Web API on .NET 4.7.2


The following does not work for me:

IContainer container;
ContainerBuilder builder = new ContainerBuilder();
container = builder.Build();
builder.RegisterInstance(container).As<IContainer>();

One of my controller require a instance of IContainer but this approach does not work for me.


Solution

  • Register a delegate, not the object.

    IContainer container = null;
    var builder = new ContainerBuilder();
    builder.Register(ctx => container).As<IContainer>();
    container = builder.Build();
    

    A hint, though - if your controller takes an ILifetimeScope instead of IContainer, the Autofac injection will automatically inject the current lifetime scope. So if you need to resolve something using service location, inject ILifetimeScope in your constructor instead of IContainer. Then you don't have to register anything.