Structuremap 3 接受注册类型/实例列表的构造函数

3

我有一个对象,它在构造函数中需要一个 IEnumerable<IPluginType> 参数。同时,在我的容器配置中,我还有一行代码用于添加所有 IPluginType 的实现者:

x.Scan(s =>
{
    ...

    s.AddAllTypesOf<IPluginType>();
});

我通过 container.WhatDoIHave() 确认了预期的实现者已经注册,但 IEnumerable 没有被填充。

我想我有点过于乐观地认为 Structuremap 会知道我的意思,我该如何告诉它呢?


IPluginType和构造函数之间有什么联系?你的意思是一个类有一个构造函数,它接受IEnumerable<IPluginType>吗? - Rhumborl
抱歉,@Rhumborl,在第一句中角括号遮挡了IPluginType。现在更清楚了吗? - A. Murray
如果您所说的 IPluginType 已经被正确地注册,那么 StructureMap 确实可以正确地解析它 - https://dotnetfiddle.net/NpehG0 - Rhumborl
你说得对,@Rhumborl,它确实可以使用我创建的设置 - 我以前使用的是抽象类型,现在我将其移动到了接口中,它就可以正常工作了。请将您的解释作为答案提供,我会标记它。 - A. Murray
1个回答

4
如果像您所说,IPluginType已经被注册到Container中,StructureMap会正确解析并将每个注册类型的一个实例传递给IEnumerable。正如您发现的那样,您需要使用接口而不是抽象类型。

以下是一个完整的工作示例(或作为dotnetfiddle):

using System;
using System.Collections.Generic;
using StructureMap;

namespace StructureMapTest
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var container = new Container();
            container.Configure(x =>
            {
                x.Scan(s =>
                {
                    s.AssemblyContainingType<IPluginType>();
                    s.AddAllTypesOf<IPluginType>();
                });

                x.For<IMyType>().Use<MyType>();
            });

            var myType = container.GetInstance<IMyType>();
            myType.PrintPlugins();
        }
    }

    public interface IMyType
    {
        void PrintPlugins();
    }

    public class MyType : IMyType
    {
        private readonly IEnumerable<IPluginType> plugins;

        public MyType(IEnumerable<IPluginType> plugins)
        {
            this.plugins = plugins;
        }

        public void PrintPlugins()
        {
            foreach (var item in plugins)
            {
                item.DoSomething();
            }
        }
    }

    public interface IPluginType
    {
        void DoSomething();
    }

    public class Plugin1 : IPluginType
    {
        public void DoSomething()
        {
            Console.WriteLine("Plugin1");
        }
    }

    public class Plugin2 : IPluginType
    {
        public void DoSomething()
        {
            Console.WriteLine("Plugin2");
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接