3

我有一个对象,它期望一个IEnumerable<IPluginType>作为它的构造函数的参数。我的容器配置中还有一行添加了 IPluginType 的所有实现者:

x.Scan(s =>
{
    ...

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

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

我想我有点乐观认为 Structuremap 会明白我的意思,我怎么能说出来?

4

1 回答 1

3

如果IPluginTypes 确实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");
        }
    }
}
于 2014-10-21T14:00:39.643 回答