Structuremap 3 constructor that takes a list of all registered types / instances
I have an object that expects IEnumerable<IPluginType>
as a parameter to a constructor. I also have a line in my container config that adds all the executors of type IPluginType:
x.Scan(s =>
{
...
s.AddAllTypesOf<IPluginType>();
});
I confirmed via container.WhatDoIHave () that the expected executors are registered, but the IEnumerable is not populating.
I think I am a little optimistic that Structuremap will know what I mean, how can I say that?
source to share
If IPluginType
definitely registered in Container
, as you say, StructureMap correctly resolves it and passes one of each registered type to IEnumerable
. As you've found, you need to use interfaces, not abstract types.
Here's a complete working example (or as 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");
}
}
}
source to share