0

I decided to use this AddDbContext method to add and setup my context for my Entity Framework Core project using ODataController

services.AddDbContext<ExampleContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ExampleConnection"))); 
// https://stackoverflow.com/a/51970589/196526

I suppose this AddDbContext allow us to add a global context and it is possible to retrieve it later when required in my controller or service class. How can I use it?

At this moment I pass my context each time.

public class StudentsController : ODataController { private readonly ExampleContext _context;

    public StudentsController(ExampleContext context)
    {
        _context = context;
    }
}

I would like to get load my context without having to pass it to my controller. I'm using ODataController.

Bastien Vandamme
  • 17,659
  • 30
  • 118
  • 200
  • 1
    *without having to pass it to my controller* -- But that's the whole idea of dependency injection. If you don't do it this way you'll revert to the less recommended service locator pattern. Also, using a global context is a bad idea. – Gert Arnold May 17 '19 at 19:58
  • If you don't wish to pass it trough the constructor you could use the [FromServices attribute](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.fromservicesattribute). – GWigWam May 20 '19 at 07:03

0 Answers0