使用 Spring.Net,可以查询某个(祖先)类型的所有对象。
var ctx = ContextRegistry.GetContext();
var setUsers = ctx.GetObjectsOfType(typeof(ISetUser)).Values.OfType<ISetUser>().ToList();
DryIoc 如何做到这一点?
使用 Spring.Net,可以查询某个(祖先)类型的所有对象。
var ctx = ContextRegistry.GetContext();
var setUsers = ctx.GetObjectsOfType(typeof(ISetUser)).Values.OfType<ISetUser>().ToList();
DryIoc 如何做到这一点?
给出示例类和接口的直接答案是:
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);
}