How can I access existing context in ASP.NET Core application? c# entity-framework-core


What am I doing?

I am making API application via ASP.NET Core. I was following this tutorial: .

What's the problem?

In the tutorial it is described how to make your own model, its context and controller. However, I can only access the context from that controller. But what if I want to access stored data from another controller, which doesn't have this context? Or maybe not from controller at all, I might want to access the context from other classes as well. Since the context class is not static, I need a way to access the same instance (which is passed to controller) from anywhere.

I guess that's actually pretty basic stuff, but I couldn't find anywhere it's described. Probably can't form my question properly in short.

The Code

In controllers the context is passed on creation:

public class AuthTokensController : ControllerBase
    private readonly AuthTokenContext _context;

    public AuthTokensController(AuthTokenContext context)
        _context = context;

Context class:

public class AuthTokenContext : DbContext
        public AuthTokenContext(DbContextOptions<AuthTokenContext> options) : base(options) { }

        public DbSet<AuthToken> AuthTokens { get; set; }
3/26/2020 11:47:40 AM

Accepted Answer

Thanks Enas Osama for providing the answer in comments.
I just had to include needed context to controller's constructor arguments list, so the context gets instantiated when I get the request.

3/26/2020 12:42:43 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow