0

Using ASP.NET MVC with .NET Core 2.2.

I have several similar databases and have a hierarchy of DbContext such as:

public class BaseContext : DbContext {}
public class DerivedContext : BaseContext {}

I have services and controllers that should work with both DbContext:

public class MyService
{
    public MyService(BaseContext dbContext) {}
}
public class MyController : ControllerBase
{
    public MyController (BaseContext dbContext) {}
}

I'm trying to use these with the derived database as follows:

services.AddDbContext<DerivedContext>(x => ...);

The problem is the dependency injector is unable to resolve the BaseContext parameters. How can I register the derived type with the dependency injection container and have it provided when the base type is requested?

denver
  • 2,863
  • 2
  • 31
  • 45
  • Try using an interface IBaseContext instead.. not sure if that works or not. – Marlon Oct 26 '19 at 04:11
  • @Marlon I believe you could do that, but I would rather not as it would just be extra code mirroring the public interface of BaseContext. It would serve no purpose other working around this issue. – denver Oct 26 '19 at 04:17

2 Answers2

1

You can manually register DeriverContext as BaseContext.

services.AddDbContext<DerivedContext>(x => ...);
services.AddScoped<BaseContext>(c => c.GetRequiredService<DerivedContext>());

It's similar to how a proxies works.

You can also write an extensions method to encapsulate context registration.

Markeli
  • 558
  • 4
  • 16
0

Thats not possible for the dependency injector he needs a concrete unique type or interface that can be resolved to specific service. For the Service you could use a generic Type to set the kind of context used by the instance of the service. But this would require also that you register the service for each kind of context one time and you have to differentiate in each controller what kind of service you want to use.

If you have similar Databases why you don't reuse the context for both of them. Whats the difference between the two context ?

Maybe it could be interesting for you to have multiple instances of the same context that configuration is different. That would be probably the best and cleanest way because the controller and services does not twig any difference between the Context. I am also using this behaviour to work with an database with multiple schemes that contain exactly the same tables. For an example look here

Retrogott
  • 110
  • 7
  • The database are not completely the same. One has some additional tables and a modified SaveChanges implementation. – denver Oct 27 '19 at 05:28