0

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; }
Asdolg
  • 23
  • 5
  • Can you elaborate more? You can simply use it anywhere you want just by referencing it by it's namespace. – Salah Akbari Mar 26 '20 at 11:24
  • @Salah Akbari but the context is not a static class, and I need to use the same instance which is passed to controller. – Asdolg Mar 26 '20 at 11:29
  • 1
    The DBContext is instantiated with every request and the DI handles its lifetime. so when you inject the DBContext you will get the same instance per request check this question https://stackoverflow.com/questions/37507691/entity-framework-core-service-default-lifetime – Enas Osama Mar 26 '20 at 12:07
  • Ohhh, so I just have to include needed context to controller's constructor arguments. That helped, as I thought it was easy af. Thanks! – Asdolg Mar 26 '20 at 12:40

1 Answers1

0

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.

Asdolg
  • 23
  • 5