【发布时间】:2022-01-21 02:45:16
【问题描述】:
...也许在 EF Core 扩展中的 AddDbContextFactory<TContext, TFactory> 中使用 TFactory?
我只看到 AddDbContextFactory examples 仅与 TContext 泛型一起使用。他们总是非常明确地说你have to use a using statement。
在类似的情况下(当我在 Angular 中使用Class 或在 .NET Core 中使用 AddScoped 时),我将变量 我想在构造函数中查看设为第一个泛型参数,第二个泛型参数实际得到什么注入。你知道的,比如:
services.AddScoped<IService, RealService>();
显然,情况并非如此
services.AddDbContextFactory<ADbContextIHaveBeenInjecting, AFactoryThatWillReturnADbContextIHaveBeenInjecting>();
我希望这将消除整个使用的需要。
有没有另一种方法可以做到这一点,而不必重新编写每个注入的 DbContext 以符合他们的规定:
public void DoSomething()
{
using (var context = _contextFactory.CreateDbContext())
{
// ...
}
}
正如我所说,我希望在工厂中使用这样的东西:
public class MyDbContextFactory : IDbContextFactory<MyDbContext>
{
public MyDbContextFactory(DbContextOptions options)
{
}
public MyDbContext CreateDbContext()
{
var ProviderName = GetProviderName();
switch (ProviderName)
{
case "System.Data.SqlClient":
return new SqlServerDbContext(new DbContextOptionsBuilder<SqlServerDbContext>().UseSqlServer(ConnectionString).Options);
case "Npgsql":
return new PostgreSqlDbContext(new DbContextOptionsBuilder<PostgreSqlDbContext>().UseNpgsql(ConnectionString).Options);
default:
throw new NullReferenceException("Missing provider name for DbContext. Should be Npgsql or System.Data.SqlClient");
}
}
}
然后,在 Startup.cs ConfigureServices 中进行设置,如:
services.AddDbContextFactory<MyDbContext, MyDbContextFactory>();
所以我可以像这样注入一个类:
public class MyController : BaseApiController
{
private readonly MyDbContext _myDbContext;
public MyController(MyDbContext myDbContext)
{
_myDbContext = myDbContext;
}
[HttpGet("GetACount")]
public IActionResult GetACount()
{
var count = _myDbContext.MyRecord.Count();
return Ok(count);
}
...
有没有办法使用 AddDbContextFactory 做到这一点? TFactory 实际上是做什么用的?有没有其他方法可以做到这一点?
【问题讨论】:
-
你希望
GetProviderName如何实现? -
这只是一个“不让人分心的例子”。小故事:注入的配置会实时更新,我们从中获取 ProviderName。
-
您不需要使用上下文工厂。只需使用 IOptions 并映射到 json 文件中的一个部分,如下所示: "DatabaseConnections": { "OracleConnections": [ { "Alias": "Optional", "ConnectionString": "Required" }, { "Alias": "Optional ", "ConnectionString": "Required" } ], "MSSqlConnections": [ { "Alias": "Optional", "ConnectionString": "Required" } ], "SqliteConnections" [ { "Alias": "Optional", " ConnectionString": "必需" } ] }
-
所有提供者都继承自 IDbConnection。你可以使用它作为你的接口注入到你的容器中。
标签: c# entity-framework-core dbcontext