c#-接受所有已注册类型/实例列表的Structuremap 3构造函数
作者:互联网
我有一个期望IEnumerable< IPluginType>的对象.作为其构造函数的参数.我的容器配置中还有一行,它添加了IPluginType的所有实现者:
x.Scan(s =>
{
...
s.AddAllTypesOf<IPluginType>();
});
我已经通过container.WhatDoIHave()确认了预期的实现者已注册,但是未填充IEnumerable.
我想我有点乐观,认为Structuremap会明白我的意思,我怎么能说出来?
解决方法:
如果IPluginTypes确实按照您所说的在Container中注册,则StructureMap会正确解析它,并将每个注册类型之一传递给IEnumerable.如您所见,您需要使用接口,而不是抽象类型.
这是一个完整的工作示例(或as a 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");
}
}
}
标签:structuremap3,constructor-injection,structuremap,c,net 来源: https://codeday.me/bug/20191121/2049478.html