'.NET 6 Api multiple repositories (factory pattern)
I'm quite new to .NET Core (always worked before with classic framework) and don't understand how to solve it.
I need to create an API that returns a common object from different databases. In this example, I connect to DB1 with a table called "Usuarios" and to a DB2 with a table called "Users". Both tables have different field names.
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
Solution 1:[1]
In the controller, you just need to add the interface like below.
public class UsuariosController : ControllerBase
{
private readonly IServiceProvider _serviceProvider;
public UsuariosController(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
[HttpGet("Get")]
public IEnumerable<DTO_Usuario> Get(int Db)
{
IUsuarioRepository usuarioRepository = Db switch
{
1 => _serviceProvider.GetRequiredService<Usuario_DB1Repository>(),
2 => _serviceProvider.GetRequiredService<Usuario_DB2Repository>(),
_ => _serviceProvider.GetRequiredService<Usuario_DB1Repository>(),
};
return usuarioRepository.GetAll();
}
}
By using Microsoft.Extensions.DependencyInjection, you can call arbitrary services.
Goodluck!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | hoang lam |