查看如何使用数据库上下文池的示例,我发现它被设计为与 ServiceCollection
一起使用。 :
var serviceProvider = new ServiceCollection()
.AddDbContextPool<AdventureWorksContext>(options => { //options })
.BuildServiceProvider();
但是Simple Injector呢?是否可以在 Simple Injector 容器中注册数据库池?
p.s.我的应用程序不是 ASP.NET MVC,它只是一个 DAL
最佳答案
ASP.NET Core 中的 EF Core DbContext 池
在 ASP.NET Core 中集成 Simple Injector 时,您将框架和第三方组件保留在 .NET Core 配置系统中。这意味着启用 Entity Framework Core 上下文池完全按照 Microsoft 记录的方式完成:
services.AddDbContextPool<BloggingContext>(
options => options.UseSqlServer(connectionString));
作为简单的注入(inject)器 does not replace the built-in configuration system ,您将不得不 instruct简单的注入(inject)器,用于从 .NET Core 配置系统自动加载缺失的注册(例如您的 DbContext
)。这可以通过使用 AddSimpleInjector
来完成。和 UseSimpleInjector
扩展方法,如此处所示。private SimpleInjector.Container container;
public void ConfigureServices(IServiceCollection services)
{
...
services.AddDbContextPool<BloggingContext>(
options => options.UseSqlServer(connectionString));
services.AddSimpleInjector(container, options =>
{
options.AddAspNetCore();
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseSimpleInjector(container);
container.Verify();
...
}
使用此设置,BloggingContext
可以注入(inject)到任何从 Simple Injector 解析的组件中,而 BloggingContext
由 Entity Framework 汇集。例如:// Application compoment registered in and resolved from Simple Injector
public class CommentIsNoSpamValidator : IValidator<PostComment>
{
private readonly BloggingContext context;
// Is injected with BloggingContext from IServiceCollection
public CommentIsNoSpamValidator(BloggingContext context)
{
this.context = context;
}
public IEnumerable<ValidationResult> Validate(PostComment command)
{
// Complex business logic here.
}
}
.NET(核心)控制台应用程序中的 EF Core DbContext 池在 .NET Core 控制台应用程序中使用 Entity Framework Core 上下文池时,解决方案将非常相似,尽管您必须进行更多设置:
public void Main()
{
var container = new Container();
var services = new ServiceCollection();
services.AddDbContextPool<BloggingContext>(
options => options.UseSqlServer(connectionString));
services.AddSimpleInjector(container);
services
.BuildServiceProvider(validateScopes: true)
.UseSimpleInjector(container);
container.Verify();
// Run application code
using (AsyncScopedLifestyle.BeginScope(container))
{
var service = container.GetInstance<MainService>();
service.DoAwesomeStuff();
}
}
所以最后,DbContext 的生命周期由 MS.DI 范围管理,但该范围由 Simple Injector 的范围管理。库中的 EF Core DbContext 池
如果您正在构建一个库,即一个非启动项目,请停止您正在做的事情。只有应用程序的启动程序集应该有 Composition Root ,并且只有 Composition Root 应该使用 DI 容器(例如 Simple Injector 或 MS.DI 的
ServiceCollection
)。应用程序中的所有其他库都应该忽略容器的(可能)存在。
关于entity-framework-core - 使用带有简单注入(inject)器的 Entity Framework 核心 DbContext 池,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52111898/