user1820619 user1820619 - 1 year ago 188
ASP.NET (C#) Question

How to dynamically resolve InstancePerLifetimeScope dependency in ASP.NET Core?

I have an ASP.NET Core project. I want to dynamically resolve a "one instance per request" dependency inside my other dependencies.

I have registered a dependency using Autofac as an InstancePerLifetimeScope dependency in my Startup class:

public IServiceProvider ConfigureServices(IServiceCollection services)
{
var builder = new ContainerBuilder();
builder.RegisterType<MyDependency>().AsImplementedInterfaces().InstancePerLifetimeScope();
return new AutofacServiceProvider(builder.Build());
}


When I use this dependency directly in controller's constructor, it works as expected - it is a new instance per request.:

public MyController(IMyDependency dependency)
{
}


I want to achieve the same in one of the dependent classes. Dependency is dynamic, so I want to resolve that from IServiceProvider:

public class MyDeepDeepDependency
{
public MyDeepDeepDependency(IServiceProvider serviceProvider)
{
var dep = serviceProvider.GetService(typeof(IMyDependency));
}
}


However, a "dep" instance is the same across all requests.

I assume there is a new scope created per request, and controller is resolved from a new scope. When resolving IServiceProvider, I always get a root IServiceProvider instead of a request one.

Is there a way to resolve IServiceProvider specific for a request? I think it's the same as HttpContext.RequestServices in controller, but I don't want to pass the reference down through all my classes.

Is there any other way to resolve a dynamic dependency once per request?

Answer Source

I ended up injecting IHttpContextAccessor:

public class MyDeepDeepDependency
{
    public MyDeepDeepDependency(IHttpContextAccessor contextAccessor)
    {
        var dep = contextAccessor.HttpContext.RequestServices.GetService(typeof(IMyDependency));
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download