我正在尝试让这样的东西工作:
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
forIDisposable
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/