I am building a multi-tenanted application. The code is shared but each client has a different database. I have code that determines the specific client's database connection string (based on an API key they are using).
I want to initialise the context using this connection string.
I approached this by passing the string to the repository constructor in the hope I could then reuse it for the context constructor but I am getting the error:
A field initializer cannot reference the non-static field, method, or property...
when I attempt to initialize an Entity Framework database context using a connection string that I have previously passed into the Repository constructor.
I have researched and understand the error (you can't initialize one instance member using an other instance member, as it may not be available at that time) but I am unsure how to work my way around it.
What I am trying to achieve is self-evident from the code:
public class GlobalCompanyRepository : IGlobalCompanyRepository
{
private readonly string _dbConnectionString;
public GlobalCompanyRepository(string dbConnectionString)
{
_dbConnectionString = dbConnectionString;
}
public IntrinsicDbContext dbContext = new IntrinsicDbContext(_dbConnectionString);
public void Add(GlobalCompany entity)
{
dbContext.GlobalCompanies.Add(entity);
dbContext.SaveChanges();
}
}