What am I doing?
I am making API application via ASP.NET Core. I was following this tutorial: https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-web-api?view=aspnetcore-3.1&tabs=visual-studio .
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:
[Route("api/[controller]")]
[ApiController]
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; }