我遇到了NetCore的DI框架的问题。我知道在DI容器中注册类型的不同方法。
特别是我对.AddSingleton
方法感兴趣。这种方法有许多重叠。
我的问题是,我想确保以不同的方式注册同一类(使用界面和类型(时,创建了两个实例,一个用于每种"注册"方式。
假设我有一个称为ISomeInterface
的接口,一个名为ImplementationOfSomeInterface
的实现。
就我而言,我希望DI系统在请求ImplementationOfSomeInterface
时创建一个实例。此外,我还有一些地方仅使用接口ISomeInterface
来定义依赖关系。
问题是DI系统返回2个ImplementationOfSomeInterface
的实例。一种是依赖关系与类相关的情况,另一个是接口给出依赖关系的情况。
我已经检查了许多文档和教程,但是它们都只是解释了AddSingleton
,AddScoped
等的差异...
// registration with the class type
services.AddSingleton<ImplementationOfSomeInterface>()
//registration with an interface and the corresponding 'same' class type
services.AddSingleton<ISomeInterface, ImplementationOfSomeInterface>();
//--------- now the usage of it -------------------
public TestClassA(SomeInterfaceImplementation instance)
{
var resultingInstA = instance;
}
public TestClassB(ISomeInterface instance)
{
var resultingInstB = instance;
}
//I would expect that resultingInstA is pointing to the very same object of
//resultingInstB => but they are different!
我希望resultingInstA
指向resultingInstB
=>的同一对象,但它们不同!
如何实现我的同一实例?
您可以通过注册类的实例而不是类型来完成。
var instance = new ImplementationOfSomeInterface();
services.AddSingleton(instance);
services.AddSingleton<ISomeInterface>(instance);
现在,任何解决ImplementationOfSomeInterface
或ISomeInterface
的尝试都将返回此处初始化的实例。