Getting DbContext when resolving a singleton

后端 未结 1 928
花落未央
花落未央 2021-01-18 11:00

Within ConfigureServices I have

services.AddDbContext(options => options.UseSqlServer(Configuration.GetConnectionString(\"De         


        
1条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-18 11:25

    AddDbContext defaults to using a scoped lifestyle:

    Scoped lifetime services (AddScoped) are created once per client request (connection).

    The reason an error is being thrown is that you're attempting to obtain an instance of MyContext from outside of a request. As the error message suggests, it is not possible to obtain a scoped service from the root IServiceProvider.

    For your purposes, you can create a scope explicitly and use that for your dependency resolution, like so:

    services.AddSingleton(sp =>
    {
        using (var scope = sp.CreateScope())
        {
            var dbContext = scope.ServiceProvider.GetService();
            var lastItem = dbContext.Items.LastOrDefault();
            return new MyModel(lastItem);
        }
    });    
    

    This code above creates a scoped IServiceProvider that can be used for obtaining scoped services.

    0 讨论(0)
提交回复
热议问题