Autofac vs. Structuremap, how can I inject all instances of an interface?

In autoFac, I can register several interface implementations. When autofac instantiates an object, all instances are passed to the constructor.

From the autofacs documentation: here

For example, when Autofac enters a constructor parameter of type IEnumerable, it will not look for the component that supplies IEnumerable. Instead, the container will find all ITask implementations and embed them all.

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 to register my implementations, so that when using the UseFoo instance, the constructor will be transferred to all IFoo implementations?

+4
source share
1 answer

In StructureMap you can do:

 ObjectFactory.Intialize(x => x.Scan(y => y.AddAllTypesOf<IFoo>())); 

This will log all types of IFoo

Then, when you enable UsingFoo , they will be introduced.

Edit:

I just wrote this in a console application:

 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 great.

Here is a working example that I quickly wrote in a console application:

 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(); } } 

Conclusion:

This is from Foo 1

This is from Foo 2

Done

+6
source

Source: https://habr.com/ru/post/1403001/


All Articles