Use DbContext in ASP .Net Singleton Injected Class
<p>I need to access my database in a Singleton class instantiated in my Startup class. It seems that injecting it directly results in a DbContext that is disposed. </p>

<p>I get the following error:</p>

<blockquote>
  <p>Cannot access a disposed object. Object name: 'MyDbContext'.</p>
</blockquote>

<p>My question is twofold: Why doesn't this work and how can I access my database in a singleton class instance?</p>

<p>Here is my ConfigureServices method in my Startup class:</p>

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

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

    // code removed for brevity

    services.AddSingleton&lt;FunClass&gt;();
}
</code></pre>

<p>Here is my controller class:</p>

<pre><code>public class TestController : Controller
{
    private FunClass _fun;

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

    public List&lt;string&gt; Index()
    {
        return _fun.GetUsers();
    }
}
</code></pre>

<p>Here is my FunClass:</p>

<pre><code>public class FunClass
{
    private MyDbContext db;

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

    public List&lt;string&gt; GetUsers()
    {
         var lst = db.Users.Select(c=&gt;c.UserName).ToList();
        return lst;
    }
}
</code></pre>