I have this piece of code in the startup.cs file of my ASP.Net Core Web API project:
public void ConfigureServices(IServiceCollection services)
{
// Retrieve the database connection string
string connectionString = "Do something to retrieve a connection string";
services.AddDbContext<MyContext>(options => options.UseSqlServer(connectionString));
}
I have reasons to do this here and not in MyContext's OnConfiguring() method, but now I am getting this error:
System.InvalidOperationException: 'No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext.'
This is my MyContext class's:
public partial class MyContext : DbContext
{
public MyContext()
{
}
public MyContext(DbContextOptions<MyContext> options)
: base(options)
{
}
...
}
I found somewhere that I also need to do this:
public class MyController : Controller
{
private MyContext _context;
public MyController(MyContext context)
{
_context = context;
}
}
but this is very inconvenient since I am currently not instantiating MyContext in the controllers, but in a different layer, for example:
public ActionResult MyMethod(...)
{
MyManager.DoSomething(); // MyManager instantiates the context
return Ok();
}
This is how I'm currently instantiating the context:
private static readonly MyContext myContext = new MyContext();
I'm guessing I need to somehow inject the options into the context, but I don't know how.