在 ASP.NET Core C# .NET 6.0 中切换存储库类型

问题描述 投票:0回答:2

我想将我的 Web API 用于不同的数据库(SQL Server 和 MongoDb)。 我有两个通用存储库:EntityRepository<> 和 MongoRepository<>。 这样我就有了这个代码

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

当我想切换DB时,我应该输入

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

并重新编译应用程序。

我想从appsettings.json切换它

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

}

如何重构此代码以通过 appsettings.json 中的字符串切换通用存储库? 或者也许您知道无需重新编译即可切换数据库的更好方法。

c# .net appsettings
2个回答
2
投票

您似乎想同时使用两种类型的存储库,在这种情况下,您应该注册两个存储库(您需要两种类型接口)并将两者注入到它们中。

更新2: dotnet 8 中的键控 DI 服务

更新1: 您可以将工厂与委托结合起来完成:

定义接口:

public interface ILog
{
void log();
}

和班级:

public class logtoFile: ILog
{void log(){//log to file}}

public class logtoDb: ILog
{void log(){//log to DataBase}}

所以我们需要一个代表:

public delegate Ilog IlogResolved(int type);

并在启动时设置ioc:

builder.services.addScope<logtoFile>();
builder.services.addScope<logtoDb>();

builder.services.addScope<IlogResolved>
(
provider => type =>
{
  return type switch
   1=> provider.getService<logtoFile>(),
   2=> provider.getService<logtoDb>(),
   _ => throw new ArgumentException(nameof(type))
};
);

然后像这样使用它:

private readOnly IlogResolved _logResolvd;
public myclass(IlogResolved logResolvd)
{_logResolvd=logResolvd;}


public void DoSomthing()
{
 var logTofile=_logResolvd(1);
 var logToDb=_logResolvd(2);

 logTofile.log("log to file");
 logTofile.log("log to db");
}

0
投票

您需要为配置服务编写扩展方法:

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>();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.