无法使用 Unity 容器解析实例

Cant resolve instance with Unity container

我像这样用 Unity 注册了一个实例:

ContentSlideControlsEntity contentSlideControlsEntity = new ContentSlideControlsEntity(new Queue<uint>());
        container.RegisterInstance(typeof(ContentSlideControlsEntity), "contentSlideControlsEntity", contentSlideControlsEntity);

然后我只想重新爱它:

ContentSlideControlsEntity contentSlideControlsEntity2 = container.Resolve<ContentSlideControlsEntity>();

但我收到以下运行时错误:

Microsoft.Practices.Unity.ResolutionFailedException: 'Resolution of the dependency failed, type = "MSDataLayer.Entities.ContentSlideControlsEntity", name = "(none)".

Exception occurred while: while resolving.

Exception is: InvalidOperationException - The type Queue`1 has multiple constructors of length 1. Unable to disambiguate.


At the time of the exception, the container was:

Resolving MSDataLayer.Entities.ContentSlideControlsEntity,(none)

Resolving parameter "slideIDQueue" of constructor MSDataLayer.Entities.ContentSlideControlsEntity(System.Collections.Generic.Queue`1[[System.UInt32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] slideIDQueue)

Resolving System.Collections.Generic.Queue`1[System.UInt32],(none)

您将您的实例注册为命名注册,但您正在解析未命名注册(不存在)。

container.RegisterInstance(typeof(ContentSlideControlsEntity), "contentSlideControlsEntity", contentSlideControlsEntity);
                                                               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^

您有 2 个选择:

1) 不要将其注册为命名注册

container.RegisterInstance(typeof(ContentSlideControlsEntity), contentSlideControlsEntity);

2) 用名称解析

container.Resolve<ContentSlideControlsEntity>("contentSlideControlsEntity");