Reputation: 8214
In autoFac, I can register multiple implementation of an interface. When autofac instantiates my object, all instances are passed to the constructor.
From autofac’s documentation: here
For example, when Autofac is injecting a constructor parameter of type IEnumerable it will not look for a component that supplies IEnumerable. Instead, the container will find all implementations of ITask and inject all of them.
Is this functionality available in StructureMap?
For my classes:
public interface IFoo
{
}
public class Foo1 : IFoo
{
}
public class Foo2 : IFoo
{
}
public class UsingFoo
{
public UsingFoo(IEnumerable<IFoo> allFoos)
{
foreach (var foo in allFoos)
{
}
}
}
How do I register my implementations, so that when UsingFoo is instantiated, the constructor will be passed all implementations of IFoo?
Upvotes: 4
Views: 2528
Reputation: 18794
In StructureMap you can do:
ObjectFactory.Intialize(x => x.Scan(y => y.AddAllTypesOf<IFoo>()));
That will register all types of IFoo
Then when you resolve UsingFoo
, they will be injected.
Edit:
I just quickly wrote this up in a console app:
ObjectFactory.Initialize(x =>
{
x.Scan(y =>
{
y.AddAllTypesOf<IFoo>();
});
});
var usingFoo = ObjectFactory.GetInstance<UsingFoo>();
Edit:
You made me doubt myself, so I double checked.
It works fine.
Here's a working example I quickly wrote in a console app:
public interface IFoo
{
string Text { get; }
}
public class Foo1 : IFoo
{
public string Text
{
get { return "This is from Foo 1"; }
}
}
public class Foo2 : IFoo
{
public string Text
{
get { return "This is from Foo 2"; }
}
}
public class Bar
{
private readonly IEnumerable<IFoo> _myFoos;
public Bar(IEnumerable<IFoo> myFoos)
{
_myFoos = myFoos;
}
public void Execute()
{
foreach (var myFoo in _myFoos)
{
Console.WriteLine(myFoo.Text);
}
}
}
class Program
{
static void Main(string[] args)
{
ObjectFactory.Initialize(x =>
{
x.UseDefaultStructureMapConfigFile = false;
x.Scan(y =>
{
y.TheCallingAssembly();
y.AddAllTypesOf<IFoo>();
});
});
var myBar = ObjectFactory.GetInstance<Bar>();
myBar.Execute();
Console.WriteLine("Done");
Console.ReadKey();
}
}
The output is:
This is from Foo 1
This is from Foo 2
Done
Upvotes: 6