DryIoc 和 UseInstance 导致 "Expecting the instance to be stored in singleton scope" 异常

DryIoc and UseInstance leads to "Expecting the instance to be stored in singleton scope" exception

当我尝试获取对象实例时,这取决于 UseInstance 注册的参数,我得到

DryIoc.ContainerException : Expecting the instance to be stored in singleton scope, but unable to find anything here. Likely, you've called UseInstance from the scoped container, but resolving from another container or injecting into a singleton.

使用 xUnit:

    public interface IFooDao { }
    public class FooDao : IFooDao
    {
        public FooDao(ConnectionStringSettings connString) { }
    }
    [Fact]
    void CompositionRootWontThrowException()
    {
        var container = new Container();
        container.Register<IFooDao, FooDao>(Reuse.Singleton);

        ConnectionStringSettings connString = ConfigurationManager.ConnectionStrings["ConnectionString"];
        container.UseInstance(connString);
        IFooDao dao = container.Resolve<IFooDao>();
    }

所以我有这个异常消息,但我找不到问题和解决方案:

1) 我没有作用域容器,因为我不是 container.OpenScope() 创建的,对吗?我只有一个容器,所以我不能从一个错误的容器中解决。它是一个容器

without context (which is default)

根据project wiki

2) 那么,我是 "injecting into a singleton" 是什么意思?我想在创建单例时将依赖项注入单例 - 这有什么问题吗?反正我在做吗?

3) 根据docs again,conn 字符串的实例应该在单例范围内

When you call the UseInstance the instance will be *directly put into Open scope or Singleton scope based on whether the container is scoped (returned from OpenScope call) or not. In addition, the scoped and sington instances may coexist with each other.

我以前用过类似的代码,只是用 DryIoc.MEF 扩展名和 ExportManyAttributeImportAttributeUseInstace 的用法与下面完全相同。一切正常。我在这里错过了什么?为什么抛出这个异常?

首先,我认为这段代码非常简单,不会失败:)

问题出在 null 注册中。

UseInstance 可以被赋予 null 值,但是当你需要实际的依赖时,即使实际的 null 被解析,它也可能被认为是不够的并抛出异常。

ConnectionStringSettings connString = ConfigurationManager.ConnectionStrings["ConnectionString"];

返回 null,因为配置中的实际连接名称输入错误。