DryIoc, Spring.Net's GetObjectsOfType equivalent?

筅森魡賤 提交于 2019-12-11 07:36:18

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/37027390/dryioc-spring-nets-getobjectsoftype-equivalent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!