Home > Enterprise >  Switch type of repository in ASP.NET Core C# .NET 6.0
Switch type of repository in ASP.NET Core C# .NET 6.0

Time:07-05

I want to use my Web API for different databases (SQL Server and MongoDb). I have two generic repositories: EntityRepository<> and MongoRepository<>. So that I have this code

builder.Services.AddTransient(typeof(IRepository<>), typeof(EntityRepository<>));

When I want to switch DB, I should enter

builder.Services.AddTransient(typeof(IRepository<>), typeof(MongoRepository<>));

and recompile application.

I want to switch it from appsettings.json

"SourceDb": {
"Entity": "EntityRepository",
"Mongo": "MongoRepository"

}

How can I refactor this code to switch generic repositories by strings from appsettings.json? Or maybe you know better way to switch databases without recompilation.

CodePudding user response:

it seems you want to use two types of repositories at the same time, in this case, you should register two repo (you needed two type interfaces) and inject both to them.

CodePudding user response:

You would need to write and extension method to your configuration service:

private static void SetRepository(this IServiceCollection services, IConfiguration configuration)
{
    string repo = configuration["SourceDb"];

    if (repo == "EntityRepository")
    {
        services.AddTransient<IRepository, EntityRepository>();
    }
    else
    {
        services.AddTransient<IRepository, MongoRepository>();
    }
}
  • Related