Structuremap 3构造函数,它接受所有已注册类型/实例的列表

本文关键字:类型 注册 实例 列表 构造函数 Structuremap | 更新日期: 2023-09-27 18:27:13

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

x.Scan(s =>
{
    ...
    s.AddAllTypesOf<IPluginType>();
});

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

我想我有点乐观,认为Structuremap会知道我的意思,我该怎么说呢?

Structuremap 3构造函数,它接受所有已注册类型/实例的列表

如果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");
        }
    }
}