【问题标题】:Can I use a dependency injection singleton in two different classes?我可以在两个不同的类中使用依赖注入单例吗?
【发布时间】:2021-09-19 22:37:38
【问题描述】:

我有一个界面:

public interface Irepos 
{
    string somefunction();
}

然后是我要使用的类:

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

在startup.cs中注册为单例:

services.AddSingleton<Irepos, repos>();

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

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

    interfaceRepos.somefunction();
}

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

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

【问题讨论】:

  • 尝试时会发生什么?
  • 是的,这就是单例的工作方式。 DI 将为两个控制器提供相同的 IRepos 实例(类型为 repos)。
  • @David 当我尝试它时,我在问这是否是一个好习惯以及为什么要使用它,如果有一些我不知道的东西我太害怕了,不知何故我得到了两个实例以后会很头疼的课程。
  • @MartinCostello 感谢您的回答
  • @Liam 我有点需要那个。

标签: c# asp.net-core dependency-injection


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-09
    • 2015-06-01
    • 1970-01-01
    • 2021-09-14
    • 2014-01-02
    • 2015-02-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多