我有一个对象,它需要一个IEnumerable<IPluginType>
作为它的构造函数的参数。我的容器配置中还有一行添加了IPluginType:的所有实现者
x.Scan(s =>
{
...
s.AddAllTypesOf<IPluginType>();
});
我已经通过集装箱确认了。WhatDoIHave(),预期的实现者已经注册,但IEnumerable没有被填充。
我想我有点乐观,认为Structuremap会知道我的意思,我该怎么说呢?
如果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");
}
}
}