作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在将我的项目从经典的 ASP.Net 升级到 Asp.Net Core 3.1。在旧项目中,我曾经像这样注册我的 UoW 和服务:
builder.Register(x => new UnitOfWork())
.As(typeof(IUnitOfWork))
.InstancePerLifetimeScope();
builder.RegisterAssemblyTypes(AppDomain.CurrentDomain.GetAssemblies())
.Where(t => t.Name.EndsWith("Service"))
.AsImplementedInterfaces()
.InstancePerLifetimeScope();
BackgroundQueue
和
QueuedService
实现和注册是这样的:
builder.RegisterType<BackgroundQueue>()
.As<IBackgroundQueue>()
.SingleInstance();
builder.RegisterType<QueuedService>()
.As<IHostedService>()
.InstancePerDependency();
backgroundQueue.QueueBackgroundWorkItem(async ct => { //Do stuff... });
InstancePerDependency
,这应该满足这两种情况吗?
最佳答案
如果后台作业使用其他服务,例如 DbContext
注册为 InstancePerLifetimeScope
,它可能需要使用具有为作业范围注册的服务的子范围:
public class MyController
{
public MyController(ILifetimeScope parentScope)
{
var builder = new ContainerBuilder();
builder.RegisterType<MyDbContext>()
.WithParameters(new[] { new TypedParameter(typeof(DbContextOptions), MasterDbContext.GetOptions(masterDbConnectionString)) })
.InstancePerLifetimeScope()
.AsSelf();
[..other services]
var container = builder.Build();
backgroundQueue.QueueBackgroundWorkItem(async ct =>
{
using(container)
{
//Do stuff...
}
});
}
}
关于c# - 在注册 Controller 和托管服务时使用 InstancePerLifetimeScope 还是 InstancePerDependency?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60910848/
我正在将我的项目从经典的 ASP.Net 升级到 Asp.Net Core 3.1。在旧项目中,我曾经像这样注册我的 UoW 和服务: builder.Register(x => new UnitOf
我对依赖生命周期的概念还很陌生。我已阅读有关 different lifetime types 的文档. 对于InstancePerDependency,默认一个。该页面讨论了在 lifetimesc
我是一名优秀的程序员,十分优秀!