Dependency injection in ASP.NET Core 2 throws exception

前端 未结 5 723
失恋的感觉
失恋的感觉 2020-12-13 09:15

I receive following exception when I try to use custom DbContext in Configure method in Startup.cs file. I use ASP.NET Core in version 2.0.0-previe

5条回答
  •  佛祖请我去吃肉
    2020-12-13 09:42

    The solution from NKosi works because by invoking services.BuildServiceProvider() yourself without parameters you are not passing the validateScopes. Because this validation is disabled, the exception is not thrown. This doesn't mean that the problem is not there.

    EF Core DbContext is registered with a scoped lifestyle. In ASP native DI, the container scope is connected to instance of IServiceProvider. Normally, when you use your DbContext from a Controller there is no problem because ASP creates a new scope (new instance of IServiceProvider) for each request and then uses it to resolve everything within this request. However during the application startup you don't have request scope. You have an instance of IServiceProvider that is not scoped (or in other words in root scope). This means you should create a scope yourself. You can do it like this:

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        var scopeFactory = app.ApplicationServices.GetRequiredService();
        using (var scope = scopeFactory.CreateScope())
        {
            var db = scope.ServiceProvider.GetRequiredService();
            var ldapService = scope.ServiceProvider.GetRequiredService();
            // rest of your code
        }
        // rest of Configure setup
    }
    

    The ConfigureServices method can remain unchanged.

    EDIT

    Your solution will work in 2.0.0 RTM without any changes since in RTM scoped service provider will be created for Configure method https://github.com/aspnet/Hosting/pull/1106.

提交回复
热议问题