我正在使用 .net6、blazor 服务器,并且正在努力在我的 program.cs 中注册两个不同的 IDbConnection 实例。
我对大多数连接使用实体框架核心,并使用上下文工厂来注册这些连接,如下所示:
builder.Services.AddDbContextFactory<MyContext>(options => options.UseSqlServer(config.GetConnectionString("MyConnection")));
然后我可以通过执行以下操作在我的服务中使用它:
private readonly IDbContextFactory<ChargingContext> _factory;
public MyRepository(IDbContextFactory<AscRespiteContext> factory)
{
_factory = factory;
}
public string GetName(int Id)
{
using (var context = _factory.CreateDbContext())
{
return context.Supplier.Where(x => x.Id == SupplierId).FirstOrDefault().DisplayName;
}
}
这种方法非常适合我的 EF 上下文内容,但我还要求能够在代码中运行直接 SQL 查询。为此,我在我的program.cs中创建了以下内容。
builder.Services.AddTransient<IDbConnection>((sp) => new SqlConnection(config.GetConnectionString("MyConnection")));
在我的服务中,我可以按如下方式使用它:
private readonly IDbConnection _storedProcCon;
public MyRepository(IDbConnection dbConnection)
{
_storedProcCon = dbConnection;
}
public string GetSomething(int Id)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("MyId", Id);
int Foo = _storedProcCon.QuerySingle<int>("GetAnId", parameters, commandType: CommandType.StoredProcedure);
}
我的问题是,我只能在 program.cs 中注册这些 IDbConnection 连接之一,因为它没有像我的 EF 连接那样绑定到上下文。如果我添加具有不同连接字符串的多个 IDbConnection,则只有注册的最后一个可用。有没有一种方法可以“命名”这些连接以允许我注册和使用多个连接?
非常感谢
如果需要传递一个参数,基于该参数需要创建对应的类实例,可以这样做
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddTransient<Func<string, INamedService>>(_ => arg => new NamedService(arg));
var app = builder.Build();
app.MapWhen(_ => true, appBuilder =>
{
appBuilder.Run(async context =>
{
var namedServiceFactory = context.RequestServices.GetRequiredService<Func<string, INamedService>>();
var firstNamedService = namedServiceFactory("First arg");
var secondNamedService = namedServiceFactory("Second arg");
await context.Response.WriteAsync(firstNamedService.GetValue() + " ||| " + secondNamedService.GetValue());
});
});
app.Run();
public interface INamedService
{
string GetValue();
}
public class NamedService(string arg): INamedService
{
public string GetValue() => arg;
}