netcore DI容器返回具有相同重载的相同注册的不同实例

时间:2019-06-28 06:00:56

标签: .net-core

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

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

我的问题是,我想确保当我以不同的方式(通过接口和类类型)注册同一类时,然后创建两个实例,每种“注册”方式一个。

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

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

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

我已经检查了许多文档和教程,但是它们都只解释了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 =>的同一对象,但是它们是不同的!

如何实现将同一实例取回?

1 个答案:

答案 0 :(得分:0)

您可以通过注册类的实例而不只是类型来实现。

var instance = new ImplementationOfSomeInterface();
services.AddSingleton(instance);
services.AddSingleton<ISomeInterface>(instance);

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

相关问题