【发布时间】: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