MyTested.AspNetCore.Mvc
MyTested.AspNetCore.Mvc copied to clipboard
Extend IWithDbContextBuilder API to allow registration of DbContext with interface
Problem overivew
I have registered my db context with custom interface:
services.AddDatabase<IPersistence, MyDbContext>(...)
The current IWithDbContextBuilder
exposes WithEntities<TDbContext
which is used to provide the db context implementation and TDbContext
is constrained to be of type DbContext
.
In my case this results two separate instances of MyDbContext
:
- Instance of
MyDbContext
, registed asMyDbContext
and used to arrange the test data. - Instance of
MyDbContext
, registed asIPersistence
, requested by my application logic.
This obviously leads to wrong test results.
Solution
An overload of WithEntities
that allows a DbContext to be provided using specific interface, in my case IPersistence
.
I have created a snapshot branch which you could checkout and test locally.
Thank you for reporting this issue. I will take a look, and deploy a fix if there is a problem in my code.
For now, I can provide the following workaround. If you register your DbContext as in this example:
services
.AddDbContext<BlogDbContext>(options => options
.UseSqlServer(
configuration.GetConnectionString("DefaultConnection"),
b => b.MigrationsAssembly(typeof(BlogDbContext).Assembly.FullName)))
.AddScoped<IBlogData>(provider => provider.GetService<BlogDbContext>());
I will implement an extension method for easier registration, though.