我有一个ConfigurationDbContext
,我正在尝试使用。 它具有多个参数,DbContextOptions
和ConfigurationStoreOptions
。
如何将此数据库上下文添加到 ASP.NET Core 中的服务中?
我在启动.cs中尝试了以下操作:
ConfigureServices
....
services.AddDbContext<ConfigurationDbContext>(BuildDbContext(connString));
....
private ConfigurationDbContext BuildDbContext(string connString)
{
var builder = new DbContextOptionsBuilder<ConfigurationDbContext>();
builder.UseSqlServer(connString);
var options = builder.Options;
return new ConfigurationDbContext(options, new ConfigurationStoreOptions());
}
AddDbContext
实现只是在 DI 中注册上下文本身及其公共依赖项。手动注册 DbContext 是完全合法的,而不是AddDbContext
调用:
services.AddTransient<FooContext>();
此外,您可以使用工厂方法来传递参数(这是回答问题(:
services.AddTransient<FooContext>(provider =>
{
//resolve another classes from DI
var anyOtherClass = provider.GetService<AnyOtherClass>();
//pass any parameters
return new FooContext(foo, bar);
});
P.S.,一般来说,您不必注册DbContextOptionsFactory
和默认DbContextOptions
来解析 DbContext 本身,但在特定情况下可能是必要的。
你可以在startup.cs中使用它。
详细信息 : https://learn.microsoft.com/en-us/ef/core/miscellaneous/configuring-dbcontext
详细示例:ASP.NET 核心 MVC 和实体框架核心入门
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddDbContext<ApplicationDbContext>(options =>options.
UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}
在IServiceCollection
中将DbContext
注册为服务,您有两个选择:(我们假设您要连接到SQL Server数据库(
使用 AddDbContext<>
services.AddDbContext<YourDbContext>(o=>o.UseSqlServer(Your Connection String));
使用 AddDbContextPool<>
services.AddDbContextPool<YourDbContext>(o=>o.UseSqlServer(Your Connection String));
正如你可能看到的,这两者在写作方面有相似之处,但实际上它们在概念方面有一些根本的区别。 @GabrielLuci对这两者之间的差异有一个很好的回应:https://stackoverflow.com/a/48444206/1666800
另请注意,可以将连接字符串存储在 appsettings.json 文件中,只需使用: Configuration.GetConnectionString("DefaultConnection")
Startup.cs
文件中的 ConfigureServices
方法读取它。
尝试这样做来注入您的 ef 上下文 - 从 IDbContext 继承上下文
1-将上下文添加到服务:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<NopaDbContext>(
options => options
.UseLazyLoadingProxies()
.UseSqlServer(Configuration.GetConnectionString("NopaDbContext")),ServiceLifetime.Scoped);}
2-注入您的上下文:
private readonly IDbContext _context;
public EfRepository(NopaDbContext context)
{
this._context = context;
}
protected virtual DbSet<TEntity> Entities
{
get
{
if (_entities == null)
_entities = _context.Set<TEntity>();
return _entities;
}
}
数据库上下文的所有参数放在类AppDbContextParams
中,并注册工厂以为 appdbcontext 创建该对象:
services.AddScoped(sp =>
{
var currentUser = sp.GetService<IHttpContextAccessor>()?.HttpContext?.User?.Identity?.Name;
return new AppDbContextParams { GetCurrentUsernameCallback = () => currentUser ?? "n/a" };
});
/.NET 6 进行了一些更改,以便更容易(并支持(同时注册 DbContext 和 DbContextPool 以满足不同的用法。
https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-6.0/whatsnew#dbcontext-factory-improvements