NetCore DI容器返回不同的实例,以进行超载同一注册



我遇到了NetCore的DI框架的问题。我知道在DI容器中注册类型的不同方法。

特别是我对.AddSingleton方法感兴趣。这种方法有许多重叠。

我的问题是,我想确保以不同的方式注册同一类(使用界面和类型(时,创建了两个实例,一个用于每种"注册"方式。

假设我有一个称为ISomeInterface的接口,一个名为ImplementationOfSomeInterface的实现。

就我而言,我希望DI系统在请求ImplementationOfSomeInterface时创建一个实例。此外,我还有一些地方仅使用接口ISomeInterface来定义依赖关系。

问题是DI系统返回2个ImplementationOfSomeInterface的实例。一种是依赖关系与类相关的情况,另一个是接口给出依赖关系的情况。

我已经检查了许多文档和教程,但是它们都只是解释了AddSingletonAddScoped等的差异...

// 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);

现在,任何解决ImplementationOfSomeInterfaceISomeInterface的尝试都将返回此处初始化的实例。

最新更新