Getting DbContext when resolving a singleton

喜夏-厌秋 提交于 2019-12-01 21:44:19

AddDbContext defaults to using a scoped lifestyle:

Scoped lifetime services are created once per request.

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<IMyModel>(sp =>
{
    using (var scope = sp.CreateScope())
    {
        var dbContext = scope.ServiceProvider.GetService<MyContext>();
        var lastItem = dbContext.Items.LastOrDefault();
        return new MyModel(lastItem);
    }
});    

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!