对象在使用子生命周期范围时没有被处理



我有一个ASP。. NET 5应用程序,仍然使用EF6,我在Autofac注册了我的服务,如下所示:

builder.RegisterType<UnitOfWork>()
.As(typeof(IUnitOfWork))
.InstancePerDependency();
builder.RegisterAssemblyTypes(assemblies)
.Where(t => t.FullName.StartsWith("MyApp") && t.Name.EndsWith("Service"))
.AsImplementedInterfaces()
.InstancePerDependency();

然后在控制器中:

//Save object of type SomeObject
using (var scope = itemScope.BeginLifetimeScope())
{
var someService = itemScope.Resolve<ISomeService>();
var savedObject = await someService.SaveAsync(objectToSave);
}

上面的代码在后台线程中循环运行。

最初我没有使用子作用域。但随后,使用诊断工具,我注意到SomeObject引用正在增加,而不是从数据上下文中删除。

所以我决定添加子作用域,以便每次都有新的实例。但这不是问题所在。它保持原样。

如果我使用子作用域,为什么会发生这种情况,我如何解决它?

您仍然在使用itemScope来解析服务。注意,scope根本没有在using中使用。

//Save object of type SomeObject
using (var scope = itemScope.BeginLifetimeScope())
{
//var someService = itemScope.Resolve<ISomeService>();
var someService = scope.Resolve<ISomeService>();
var savedObject = await someService.SaveAsync(objectToSave);
}

最新更新