MyTested.AspNetCore.Mvc icon indicating copy to clipboard operation
MyTested.AspNetCore.Mvc copied to clipboard

Extend IWithDbContextBuilder API to allow registration of DbContext with interface

Open achobanov opened this issue 4 years ago • 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.

achobanov avatar May 01 '20 16:05 achobanov

Thank you for reporting this issue. I will take a look, and deploy a fix if there is a problem in my code.

ivaylokenov avatar May 04 '20 05:05 ivaylokenov

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.

ivaylokenov avatar May 15 '20 17:05 ivaylokenov