c# - 使用 ASP.NET Core DI 注入(inject)工厂 Func

标签 c# dependency-injection .net-core

我正在尝试让这样的东西工作:

public class FooService : IFooService {
    public FooService(Func<IBarService> barFactory) { ... }
}
public class BarService : IBarService, IDisposable { ... }

services.AddSingleton<IFooService, FooService>();
services.AddTransient<IBarService, BarService>();
services.AddSingleton<Func<IBarService>>(ctx => () => ctx.GetService<IBarService());

就解析 BarService 实例而言,这是可行的,但我不知道如何正确管理它的生命周期。当我在 FooService 的成员之一中执行此操作时:

using (var bar = _barFactory())
{
    ...
}

我得到一个ObjectDispoedException:

System.ObjectDisposedException: Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.

但是,如果我只是执行 var bar = _barFactory();,没有 using 语句,我就无法向 DI 容器发出我已完成实例的信号,并且它可以丢弃。

这里正确的做法是什么?


(旁注:是的,我知道有些人会反对单例服务不应依赖于 transient 服务。这不是这里发生的事情;单例服务依赖于单例工厂 ,它会产生 transient 实例。然后单例将 transient 服务用于一个或两个语句,然后用它完成,所以这里应该没有实际的生命周期问题。)

最佳答案

documentation 中所述:

The container will call Dispose for IDisposable types it creates. However, if you add an instance to the container yourself, it will not be disposed.

所以不要使用 using 语句,一切都应该没问题。

关于c# - 使用 ASP.NET Core DI 注入(inject)工厂 Func,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44890650/

相关文章:

javascript - 如何将文件连同数据从 Angular 上传到 .NET Core

c# - ObjectDataSource 未在配置数据源中显示数据对象

c# - 如何确定 wpf datagrid 单元格是否处于编辑模式?

c# - ASP.NET Core 2.0 翻译始终为英文

C# 声称我的 SQLite 表不存在,但它确实存在

java - 何时和何时不使用 IOC/依赖注入(inject)?

.net - Autofac + SignalR

c# - 依赖注入(inject)机制以提供通用服务接口(interface)的最具体实现

entity-framework - Entity Framework 核心3.1抛出 “Include has been used on non entity queryable”异常

c# - 数据库脚手架在 .Net Core 1.1 中停止工作