在 Unity 中解析和注册项目数组

Resolving and registering an array of items in Unity

我想通过 Unity 将一组配置项注入到构造函数中。

这是一个说明我目前所拥有的示例,它无法将我希望的数组插入到我的构造函数中:

class ArgumentType
{
    public ArgumentType(string p1) { _p1 = p1; }
    private string _p1;
    public string P1 { get { return _p1; } }
}

class ConsumingType : IConsumingType /* interface omitted here */
{
    public ConsumingType( ArgumentType[] myArguments )
    {
       ...
    }
}

class Application
{
    private UnityContainer _container;
    public static void Main()
    { 
        _container = new UnityContainer()
        _container.RegisterType<ArgumentType[]>( new InjectionFactory(c => {
            return new ArgumentType[] {
                new ArgumentType("Foo"),
                new ArgumentType("Bar"),
                new ArgumentType("Baz") }; ) );
        _container.RegisterType<IConsumingType, ConsumingType>();

        var myUsefulThing = _container.Resolve<IConsumingType>();
        /* Do useful stuff */
    }
}

我为 "Injecting array of objects using Unity" 等搜索词找到的所有答案都找到了示例,其中 Unity returns 一个 接口的不同实现数组 ,例如Injecting arrays with Unity

我知道 MSDN 站点上有大量示例(例如 https://msdn.microsoft.com/en-us/library/ff660882(v=pandp.20).aspx#config_array_runtime ) 但我没有找到任何真正涵盖我的用例的内容。我也想仅在代码中执行此操作(而不是在 app.config 中)。

如果这行不通,一个明显的解决方法是创建一个类型来保存我的数组——这将是一个足够简单的解决方案,但我确信这应该可以通过 InjectionFactoryInjectionConstructor,或他们的兄弟姐妹之一。

我认为您可以直接在 Unity 中注册 ArgumentType,而不是通过实例注册和排列。但是您需要为每个 ArgumentType 使用一个名称。

解析您的 ConsumingType 时,unity 足够聪明,可以将所有已注册的 ArgumentType 作为数组注入。

_container.RegisterInstance<ArgumentType>("Foo", new ArgumentType("Foo"));
_container.RegisterInstance<ArgumentType>("Bar", new ArgumentType("Bar"));
_container.RegisterInstance<ArgumentType>("Baz", new ArgumentType("Baz"));
_container.RegisterType<IConsumingType, ConsumingType>();

var myUsefulThing = _container.Resolve<IConsumingType>();