I have an ASP.NET Core application, which is structured in three layers i.e.:
- Data access layer (Entity Framework)
- Business logic layer
- ASP.NET MVC web application
As it is right now, the configuration works, and I can access my database in my web application library. However, when I constructed my data access layer with EF Db first, I got a generic class, which looks something like this:
public partial class ClassContext: DbContext
{
public ClassContext(DbContextOptions<ClassContext> options)
: base(options)
{
}
public virtual DbSet<Entity> Entity{ get; set; }
....
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer("ConnString");
}
}
}
As you can see, the connection string is hardcoded into my OnConfiguring method, which is not recommended.
Therefore, I followed the following "guide" here, which suggest me to use the built in DI, to pass the connection string from my Web library.
This I did:
public void ConfigureServices(IServiceCollection services)
{
//Add connectionstring to EF
services.AddDbContext<ClassContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ConnectionStringFromAppSettings")));
}
According to the "guide" the connectionstring should be provided to the constructor of my ClassContext class - and it sort of does, however not with any connection string..
This means, that optionsBuilder.IsConfigured evaluates false, and wants to use the hard coded connectionstring.
Therefore, I would very much like to know, if I use the DI incorrect, since i cannot access the connection string in my ClassContext class
Update
I removed the OnConfiguring() method, and do now inject the context into my service class constructor in the business logic layer the following way:
public MasterService(ClassContext context)
{
MinorService = new MinorService(context);
}
public Stuff AddStuffIntoDatabase(Stuff test)
{
//business logic going before here
MinorService.addstuffMethod(test)
}
However, now I get the following error, when I want to do an operation in my database:
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.
This did not happen before, when I configured the connectionstring wrongly in my OnConfiguring() method.