needTobeanSRE
needTobeanSRE

Reputation: 59

How to use Multiple DataContexts(DbContext) in a Repository .Net Web API

I am developing a web API in .NET Core with multiple DataContexts(DbContext). I have used repository pattern to handle DB calls. The Repository class accepts a DbContext as a generic type.

public class Repository<T> : IRepository where T : DbContext
{
      public Repository(T context) : base(context)
      {
      }
}

This Repository class injects to service classes as IRepository from the Startup. I want to connect with 2 databases. So I`m using 2 DataContext classes and passed them in to repository class in the startup.

Here is my Startup class,

services.AddTransient<DataContext1>(x => new DataContext1(Configuration.GetConnectionString("Database1")));
services.AddTransient<IRepository, Repository<DataContext1>>();
            
services.AddTransient<DataContext2>(x => new DataContext2(Configuration.GetConnectionString("Database2")));
services.AddTransient<IRepository, Repository<DataContext2>>();

When I request IRepository it always injects the Repository class with the last DataContext(DataContext2). What is the best way to solve this problem without affecting to the API performance(Memory / CPU).

Here is my Service class,

private readonly IRepository _repository;

public BookService(IRepository repository)
{
    _repository = repository;
} 

Upvotes: 0

Views: 797

Answers (2)

Moho
Moho

Reputation: 16573

Inject a factory class for the repositories instead of an instance of the repositories themselves. Implement the factory methods to suit your needs.

Upvotes: 0

Lucas SIlva
Lucas SIlva

Reputation: 96

I think you should at least create one repository interface for each type of database in order of the dependency injection system can handle it.

Upvotes: 1

Related Questions