简体   繁体   English

使用ASP.NET Core DI注入工厂Func

[英]Injecting a factory Func with ASP.NET Core DI

I'm trying to get something like this working: 我想尝试这样的工作:

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());

This works as far as resolving the BarService instance, but I can't figure out how to properly manage its lifetime. 这可以解析BarService实例,但我无法弄清楚如何正确管理它的生命周期。 When I do this inside one of the members of FooService : 当我在FooService一个成员中执行此FooService

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

I get an ObjectDispoedException : 我得到一个ObjectDispoedException

System.ObjectDisposedException: Cannot access a disposed object. System.ObjectDisposedException:无法访问已处置的对象。 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. 如果您在上下文中调用Dispose()或将上下文包装在using语句中,则可能会发生这种情况。 If you are using dependency injection, you should let the dependency injection container take care of disposing context instances. 如果使用依赖项注入,则应该让依赖项注入容器负责处理上下文实例。

However, if I just do var bar = _barFactory(); 但是,如果我只做var bar = _barFactory(); , without the using statement, I have no way to signal to the DI container that I'm done with the instance, and it can be disposed. ,没有using语句,我无法向DI容器发信号通知我已经完成了实例,并且可以将其处理掉。

What's the correct approach here? 这里的正确方法是什么?


(Side note: yes, I know that some will object that a singleton service should not be dependent on a transient service. That's not what's happening here; the singleton service is dependent on a singleton factory , that produces transient instances. The singleton then uses the transient service for one or two statements and then is done with it, so there should be no actual lifetime problems here.) (旁注:是的,我知道有些人会反对单件服务不应该依赖于瞬态服务。这不是这里发生的事情;单件服务依赖于单件工厂 ,它产生瞬态实例。然后单例使用一个或两个语句的瞬态服务然后用它来完成,所以这里应该没有实际的生命周期问题。)

As described in documentation : 文档中所述

The container will call Dispose for IDisposable types it creates. 容器将为其创建的IDisposable类型调用Dispose However, if you add an instance to the container yourself, it will not be disposed. 但是,如果您自己将容器添加到容器中,则不会将其丢弃。

So just don't use using statement and all should be OK. 所以只是不要使用using语句,一切都应该没问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM