相关疑难解决方法(0)

在ASP .Net Singleton注入类中使用DbContext

我需要在我的Startup类中实例化的Singleton类中访问我的数据库.似乎直接注入它会导致处理掉的DbContext.

我收到以下错误:

无法访问已处置的对象.对象名称:'MyDbContext'.

我的问题有两个:为什么这不起作用,如何在单例类实例中访问我的数据库?

这是我的Startup类中的ConfigureServices方法:

public void ConfigureServices(IServiceCollection services)
{
    // code removed for brevity

    services.AddEntityFramework().AddSqlServer().AddDbContext<MyDbContext>(
        options =>
        {
            var config = Configuration["Data:DefaultConnection:ConnectionString"];
            options.UseSqlServer(config);
        });

    // code removed for brevity

    services.AddSingleton<FunClass>();
}
Run Code Online (Sandbox Code Playgroud)

这是我的控制器类:

public class TestController : Controller
{
    private FunClass _fun;

    public TestController(FunClass fun)
    {
        _fun = fun;
    }

    public List<string> Index()
    {
        return _fun.GetUsers();
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的FunClass:

public class FunClass
{
    private MyDbContext db;

    public FunClass(MyDbContext ctx) {
        db = ctx;
    }

    public List<string> GetUsers()
    {
         var lst …
Run Code Online (Sandbox Code Playgroud)

c# dependency-injection asp.net-core

28
推荐指数
5
解决办法
2万
查看次数

标签 统计

asp.net-core ×1

c# ×1

dependency-injection ×1