Search code examples
prismunity-container

How can I inject all instances as collection IEnumerable<T> that implement a common interface in Prism?


I want to inject all instances as IEnumerable<T> that implement a common interface. It is for using it in a strategy pattern resolver. How can I do it? I googled that unity container has a way.

I need this to do the same job as link below.

https://ufukhaciogullari.com/blog/strategy-pattern-with-dependency-injection/

    public interface ITest
    {
        string Name { get; set; }
    }

    public class TestA : ITest
    {
        public string Name { get; set; } = "A";
    }

    public class TestB : ITest
    {
        public string Name { get; set; } = "B";
    }

    public class TestC : ITest
    {
        public string Name { get; set; } = "C";
    }

    public class SomeResolver
    {
        IEnumerable<ITest> _tests;

        public SomeResolver(IEnumerable<ITest> tests)
        {
            _tests = tests;
        }
    }

In unity, I can register the following way:

container.RegisterType<IEnumerable<IParserBuilder>, IParserBuilder[]>();

I tried to do the same in Prism, but it fails. How to do it in Prism?


Solution

  • I tried to do the same in Prism, but it fails. How to do it in Prism?

    Prism's no dependency injection container, it just tries to hide IUnityContainer from you.

    That being said, there's no need to register the IEnumerable<IParserBuilder> in the first place.

    container.Resolve<SomeResolver>()
    

    will call the constructor and pass it instances of TestA, TestB and TestC, given you registered them first.

    container.Register<ITest, TestA>( "A" );
    container.Register<ITest, TestB>( "B" );
    container.Register<ITest, TestC>( "C" );
    

    Unfortunately, there's no way to have those A, B and C injected, too, so you have to keep the Name property if you need to identify a specific service (I'd make it read-only, though). I'd love to be able to inject IEnumerable<(string, ITest)> and get the names, too...