.NET 6 Api multiple repositories

Eligio Morgado 61 Reputation points


I came from here: net-6-web-api-entity-framework-core-with-multiple.html

I'm quite new to .NET Core (always worked before with classic framework) and don't understand how to solve it.

Let explain the situation. In this example I work with 2 databases, but the idea is to add more in the future. So please think on a solution with N databases.

I have 2 models, separated in folders. Each model has its own context and a User object.


As each database has a different User table property (different field names, etc), I have created a common object:


The idea is that when you use the Api for getting all users, you get IEnumerable<DTO_Usuario>

Then I have one repository for each database:


The interface defines a GetAll method:


And then, each repository implements the interface:

For context 1:


For context 2:


Now, let's look to the controller:


Looking at the controller:

  • I don't want to set each repository in the constructor, because when in the future I add a third database, I need to change all controllers' constructors.
  • I want, on each method, get a parameter to select the database to connect. In the example, the Get method has the db parameter which select the repository to use. But, of course, I don't want on each method do a switch to select the repository to use.

How is the best way to solve it?

I show also my Program.cs:


Thanks for your help

Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
694 questions
A set of technologies in the .NET Framework for building web applications and XML web services.
4,130 questions
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,181 questions
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 54,626 Reputation points

    the service would return a collection of repositories. the simplest implementation is to register all the dbcontexts and add to the service contractor

    // define class
    public class Repos
        pubic List<IUsuario_DB1Repository> All = new  List<IUsuario_DB1Repository>();
        public Repos(Usuario_DB1Repository rep1, Usuario_DB2Repository rep2) 
    // add to services
    //in controller
    private Repo _repos;
    public UsuariosController(Repos repos)
        _repos = repos;
    public IEnumable<DTO_Usuario> Get(int db) => _repos[db].GetAll();
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Eligio Morgado 61 Reputation points

    @Bruce (SqlWork.com)
    Thanks, I see clear your code. I will do it in that way.

    Many thanks

    0 comments No comments