我可以在两个不同的 类 中使用依赖注入单例吗?

Can I use a dependency injection singleton in two different classes?

我有一个界面:

public interface Irepos 
{
    string somefunction();
}

然后class我想用:

public class repos : Irepos
{
    string somefunction()
    {
        return "function called";
    }
}

在startup.cs中注册为单例:

services.AddSingleton<Irepos, repos>();

现在我可以在我的控制器中像这样使用它了 class:

public class controller 
{
    private readonly Irepos interfaceRepos;
    
    public ValuesController(Irepos reposInerface)
    {
        interfaceRepos = reposInerface;
    }

    interfaceRepos.somefunction();
}

现在我的问题是:我可以在不同的 class 或不同的控制器中使用相同 repos class 的相同实例吗?说:

public class AnotherController
{
    private readonly Irepos interfaceRepos;
        
    public ValuesController(Irepos reposInerface)
    {
        interfaceRepos = reposInerface;
    }
    
    interfaceRepos.somefunction();
}

根据定义,只存在一个单例实例。

您的控制器可以并行执行。

如果所讨论的对象是线程安全的(例如,它可能包含查找表或其他只读值),则使用单例是合理的并且可能是可取的。

如果对象不是线程安全的,作用域生命周期可能是合适的选择。