...也许在 EF Core 扩展中的
AddDbContextFactory<TContext, TFactory>
中使用 TFactory?
我只看到 AddDbContextFactory examples 仅与 TContext 泛型一起使用。他们总是非常明确地说你必须使用 using 语句。
在类似的情况下(当我在 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 配置服务中进行设置,如下所示:
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 的实际用途是什么?还有其他方法可以做到这一点吗?
旨在要求您管理 DbContext 的生命周期,因为 Blazor 服务器应用程序不像 ASP.NET Core 那样使用 Scope-per-Http 请求,因此 Scoped DbContext 不起作用。 如果您想要一个 Scoped DbContext,只需使用
.AddDbContext
而不是
.AddDbContextFactory
。如果您已经注册了 DbContextFactory 但仍想直接在服务中注入作用域 DbContext,请像这样注册它:
services.AddScoped<MyDbContext>(sp =>
{
var cf = sp.GetRequiredService<IDbContextFactory<MyDbContext>>();
var db = cf.CreateDbContext();
return db;
});
在启动时定义子类存储库模式
公共无效ConfigureServices(IServiceCollection服务)
var connectionString = Configuration.GetConnectionString("ABCContext_DbCoreConnectionString");
services.AddDbContext<ABCContext>(options1 => options1.UseSqlServer(connectionString));
services.AddTransient<IRepositoryMySubclass, RepositoryMySubclass>();
子类
public RepositorySubclass(ABCContext dbContext) : base(dbContext)
{
_dbContext = dbContext;
}