DryIoc,Spring.Net的GetObjectsOfType等价?

时间:2016-05-04 12:09:09

标签: spring.net dryioc

使用Spring.Net,可以查询某个(祖先)类型的所有对象。

        var ctx = ContextRegistry.GetContext();

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

如何使用DryIoc完成这项工作?

1 个答案:

答案 0 :(得分:1)

给出样本类和接口的直接答案是:

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

如果你想要检索一些界面,最好从一开始就注册它(计划它):

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