Search code examples
spring.netdryioc

DryIoc, Spring.Net's GetObjectsOfType equivalent?


With Spring.Net, it's possible to query all objects of a certain (ancestor) type.

        var ctx = ContextRegistry.GetContext();

        var setUsers = ctx.GetObjectsOfType(typeof(ISetUser)).Values.OfType<ISetUser>().ToList();

How can this be done with DryIoc?


Solution

  • The direct answer given sample classes and interfaces would be:

    public interface IA { }
    public interface IB { }
    public class AB : IA, IB { }
    public class AA : IA { }
    
    [Test]
    public void Resolve_all_services_implementing_the_interface()
    {
        var container = new Container();
        container.Register<IB, AB>();
        container.Register<AA>();
    
        // resolve IA's, even if no IA service type was registered
        var aas = container.GetServiceRegistrations()
            .Where(r => typeof(IA).IsAssignableFrom(r.Factory.ImplementationType ?? r.ServiceType))
            .Select(r => (IA)container.Resolve(r.ServiceType))
            .ToList();
    
        Assert.AreEqual(2, aas.Count);
    }
    

    If you will want to retrieve some interface, it probably good to register it from the start (plan for it):

    [Test]
    public void Resolve_automatically_registered_interface_services()
    {
        var container = new Container();
    
        // changed to RegisterMany to automatically register implemented interfaces as services
        container.RegisterMany<AB>();
        container.RegisterMany<AA>();
    
        // simple resolve
        var aas = container.Resolve<IList<IA>>();
    
        Assert.AreEqual(2, aas.Count);
    }