ivaylokenov/MyTested.AspNetCore.Mvc

Extend IWithDbContextBuilder API to allow registration of DbContext with interface

achobanov opened this issue · 2 comments

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:

  1. Instance of MyDbContext, registed as MyDbContext and used to arrange the test data.
  2. Instance of MyDbContext, registed as IPersistence , 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.