gpt4 book ai didi

c# - 在注册 Controller 和托管服务时使用 InstancePerLifetimeScope 还是 InstancePerDependency?

转载 作者:行者123 更新时间:2023-12-04 10:19:47 25 4
gpt4 key购买 nike

我正在将我的项目从经典的 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();

现在,在新项目中,我使用在 Controller 操作中调用的托管服务。所以我创建了一个 BackgroundQueueQueuedService实现和注册是这样的:
builder.RegisterType<BackgroundQueue>()
.As<IBackgroundQueue>()
.SingleInstance();

builder.RegisterType<QueuedService>()
.As<IHostedService>()
.InstancePerDependency();

Controller 操作可能使用一项特定服务。在这种情况下,生命周期范围就足够了,因为实例在请求结束时被处理掉。现在,一个特定的 Controller 操作将产生一个新的排队服务,例如:
backgroundQueue.QueueBackgroundWorkItem(async ct => { //Do stuff... });  

任务可能需要使用相同特定服务的实例。在这种情况下,任务需要创建一个全新的实例,因为在请求结束后任务将继续运行很长时间。

因此,如果我将 UoW 和所有服务始终注册为 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com