[英]Dependency injection for external classes with constructor arguments as singleton
[英]Can I use a dependency injection singleton in two different classes?
我有一个界面:
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();
}
根据定义,只有一个单例实例存在。
您的控制器可以并行执行。
如果有问题的对象是线程安全的(例如,它可能包含查找表或其他只读值),则使用单例是合理的,并且可能是可取的。
如果对象不是线程安全的,范围生命周期可能是合适的选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.