简体   繁体   中英

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?

I ended up injecting IHttpContextAccessor:

public class MyDeepDeepDependency
{
    public MyDeepDeepDependency(IHttpContextAccessor contextAccessor)
    {
        var dep = contextAccessor.HttpContext.RequestServices.GetService(typeof(IMyDependency));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM