Home » c# » c# – ASP.NET Core 3.x – Access IoC Container-Exceptionshub

c# – ASP.NET Core 3.x – Access IoC Container-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

In ASP.NET Core 3.x, the usage of IoC containers like Autofac changed. Instead of returning some adapter instance in ConfigureServices, we have to use the new ConfigureContainer method.

My question is: how can I access the Autofac IContainer instance in the Configure method? I tried to call containerBuilder.Build within ConfigureContainer, to get a reference to the container instance, but then I get an exception that the container can only built once.

I am well aware that in normal use cases, there should be no need to pass around the container (Service Locator anti pattern etc…..). However, in this special case, we are using a middleware that resolves Command and Event handler types and it is based on Autofac. It needs the container instance.

Any chance to reference the IContainer instance once it has been built by the framework?

How to&Answers:

If you really need to have dependency on the container you should add a dependency on ILifetimeScope and then resolve from this scope.

public class FooMiddleware
{
    public FooMiddleware(RequestDelegate next)
    {
        this._next = next;
    }

    private readonly RequestDelegate _next;


    public async Task InvokeAsync(HttpContext context, ILifetimeScope scope)
    {
        scope.Resolve<Foo>(); 
        await this._next(context);
    }
}