1

I have a scenario where there are multiple classes that implement the same interface. the consuming class is to get all the interface implementations as a list so that it can invoke method on all the instances.

public interface IDoSomething
{
    void Do();
}

public class Dance : IDoSomething
{
    public void Do() { }
}

public class Eat : IDoSomething
{
    public void Do() { }
}


public class Person
{
    public Person(IEnumerable<IDoSomething> actions)
    {
        foreach (IDoSomething ds in actions)
        {
            ds.Do();
        }
    }
}

How do I register the types so that class Person can resolve all the types that implement IDoSomething. This was possible with Unity, MEF and Spring.NET IOC containers. Trying to do the same with Dry IOC.

Steven
  • 166,672
  • 24
  • 332
  • 435
TrustyCoder
  • 4,749
  • 10
  • 66
  • 119
  • Not sure about DryIoC but .NET Core IoC was able to resolve it out of the box. You just register the services as always 'services.AddSingleton()' and leave the **IEnumerable** in constructor. Did you try it? – Krzysztof Skubała Mar 09 '22 at 23:39
  • I am using Dry IOC with Prism framework – TrustyCoder Mar 09 '22 at 23:43
  • Are you asking how to get all the types in your program that implement that interface? Or are you asking more about the registration part? – Kirk Woll Mar 10 '22 at 00:04
  • how to register the types so that the resolution will succeed. – TrustyCoder Mar 10 '22 at 00:29
  • 1
    Did you read https://github.com/dadhi/DryIoc/blob/master/docs/DryIoc.Docs/RegisterResolve.md#registration-api ? – Oliver Mar 10 '22 at 07:27
  • This seems to me a case of RTM: https://github.com/dadhi/DryIoc/blob/master/docs/DryIoc.Docs/RegisterResolve.md#registering-multiple-implementations. – Steven Mar 10 '22 at 09:47

1 Answers1

1

You just need to register multiple things as usual with the same interface and whatever implementations. Then inject IEnumerable of your interface, or you may use any other collection interface implemented by .NET array.

Example:

var container = new Container();
container.Register<IDoSomething, Dance>();
container.Register<IDoSomething, Eat>();
container.Register<Person, Person>();

For more information, see the documentation.

Steven
  • 166,672
  • 24
  • 332
  • 435
dadhi
  • 4,807
  • 19
  • 25