Search code examples
dryioc

DryIoc RegisterMany implementations of interface


Looking at the wiki for DryIoc, it seems the examples show the reverse of what I need, and I was wondering if the reverse is possible?

Wiki (partial example)

public interface X {}
public interface Y {}

public class A : X, Y {}
public class B : X, IDisposable {}


// Registers X, Y and A itself with A implementation 
container.RegisterMany<A>();

...

I would like to do the following

container.RegisterMany<X>();

// This would return one implementation each of A and B
container.ResolveMany<X>();

However that gives this error: "Registering abstract implementation type X when it is should be concrete. Also there is not FactoryMethod to use instead."

Is this possible out of the box or do I need to implement it myself by getting all implementations of an interface from an assembly and loop over it and register it accordingly?

UPDATE

I see that this example was maybe a little to simple for my case, but for the example above, the code @dadhi provided works great.

Here is a bit more "complex" case

namespace Assembly.A
{
    interface IImporter { }

    abstract class ImporterBase : IImporter { }
}

namespace Assembly.B
{
    interface IStuffImporter : IImporter { }
    interface IOtherImporter : IImporter { }

    class StuffImporter : ImporterBase, IStuffImporter { }
    class OtherImporter : ImporterBase, IOtherImporter { }
}

namespace Assembly.C
{
    class Program
    {
        void Main()
        {
            var container = new Container();

            container.RegisterMany( new[] { typeof(StuffImporter).Assembly }, type => type.IsAssignableTo(typeof(IImporter)) && type.IsClass && !type.IsAbstract);
            //I would like DryIoc to do the following behind the scenes
            //container.Register<IStuffImporter, StuffImporter>();
            //container.Register<IOtherImporter, OtherImporter>();

            var importers = container.ResolveMany<IImporter>();

            importers.Should().HaveCount(2);
            importers.First().Should().BeOfType<StuffImporter>().And.BeAssignableTo<IStuffImporter>();
            importers.Last().Should().BeOfType<OtherImporter>().And.BeAssignableTo<IOtherImporter>();
        }
    }
}

Would something like this be doable out of the box? Or do I need to make my own extension methods etc? It wouldn't be that much of a trouble really, and I would probably be done with it in a short time, however I would like to know for future references and to learn the DryIoc container. Thnxs in advance. :)


Solution

  • There is RegisterMany overload which accepts assemblies and service type condition (one of the examples in the wiki):

    container.RegisterMany(new[] { typeof(A).Assembly }, 
        serviceTypeCondition: type => type == typeof(X));
    

    Above registers all implementations of X from assembly of A.