【发布时间】:2021-09-14 00:20:09
【问题描述】:
我在将传递给我的 Asegurador 类的构造函数的依赖项注入时遇到问题。
当我要实例化时,_instance = new Asegurador();我没有构造函数(IGeneralRepository)需要的参数,请问如何解决?
请注意,我的 Asegurador 类是单例。
private Asegurador(IGeneralRepository generalRepository)
{
_token = GetTokenAsync().Result;
_repository = generalRepository;
}
public static Asegurador Instance
{
get
{
if (_instance == null)
{
_local = System.Environment.GetEnvironmentVariable("SEGUROS_LOCAL") ?? "local";
_instance = new Asegurador();
}
return _instance;
}
}
【问题讨论】:
-
依赖注入的全部意义在于你永远不会写
new Asegurador(...),你要求容器给你一个Asegurador的实例,它会帮你解决。跨度> -
单例的意义在于,只要你想使用它,就可以随时获取相同的实例。在 DI 容器中将类注册为单例可以做同样的事情,但不必保留静态字段以确保其生命周期跨越整个运行。
-
依赖注入是一种应用于易失性依赖的实践。由于其行为和依赖关系,您的
Asegurador是Volatile Dependency,因此您在此处尝试应用 DI 是正确的。 The Singleton pattern should only be used either from within the Composition Root or when the Dependency is Stable. -
答案对我来说并不完全清楚,我想要的是将 IGeneralRepository generalRepository 依赖项注入到我的 Asegurador 类中。问题是当我想创建新的 Asegurador() 类时,因为我目前没有 generalRepository 对象。
标签: .net-core dependency-injection singleton