Reputation: 1474
In my ASP.NET MVC project (written in C#), I want to use the right DbContext
according some value from some condition. That DbContext
should be available for all the methods of the controller. To do that, I used the following approach:
First, I built the application with all the contexts I need:
builder.Services.AddDbContext<Context1>(options => options.UseMySql(conection1, ServerVersion.AutoDetect(conection1)));
builder.Services.AddDbContext<Context2>(options => options.UseMySql(conection2, ServerVersion.AutoDetect(conection2)));
builder.Services.AddDbContext<Context3>(options => options.UseMySql(conection3, ServerVersion.AutoDetect(conection3)));
....
Second, for each DbContext
added to the builder, I created the respective model class:
namespace Project.Models
{
public class Context1 : Context0
{
public Context1(DbContextOptions<Context0> options): base(options)
{
}
public DbSet<Table1> Table1 { get; set; }
public DbSet<Table2> Table2 { get; set; }
// ....
}
}
namespace Project.Models
{
public class Context2 : Context0
{
public Context2(DbContextOptions<Context0> options): base(options)
{
}
public DbSet<Table1> Table1 { get; set; }
public DbSet<Table2> Table2 { get; set; }
// ....
}
}
Were Context0
has its own model class:
namespace Project.Models
{
public class Context0 : DbContext
{
public Context0(DbContextOptions options): base(options)
{
}
public DbSet<Table1> Table1 { get; set; }
public DbSet<Table2> Table2 { get; set; }
// ....
}
}
All the models have the same set of DbSets
.
Third, my goal is to use the Context0
on my controller after I assign the right injected context:
namespace Project.Controllers
{
public class HomeController : Controller
{
private Context0 MainContext;
private readonly Context1 InjectedContext1;
private readonly Context2 InjectedContext2;
private readonly Context3 InjectedContext3;
// ....
public HomeController(Context1 context1,
Context2 context2,
Context3 context3,
....)
{
InjectedContext1 = context1;
InjectedContext2 = context2;
InjectedContext3 = context3;
// ....
if (some condition)
{
MainContext = InjectedContext2;
}
}
}
}
The problem: when I try to use the MainContext
on any method of the controller, I get an error:
System.ArgumentNullException: 'Value cannot be null.'
The error is raised on this line:
Data1 = MainContext.Table1.ToList();
Where MainContext
is null.
However (this is important):
#1: the InjectedContext2
is correctly assigned to MainContext
(I can see that at runtime)
#2: the InjectedContext2
is properly injected to the controller (when I write InjectedContext2.Table1.ToList()
instead of MainContext.Table1.ToList()
, I got no error and the method works fine)
It looks like the lifecycle of the MainContext
doesn't endure through the controller, if you know what I mean. It's assigned, yes, but doesn't have any data "inside" of it.
Does anyone have a solution? Thanks
Upvotes: 0
Views: 59