Get a list of all registered objects implementing a certain interface

前端 未结 6 1886
失恋的感觉
失恋的感觉 2020-12-05 05:23

Consider the following

builder.Register(c => new A());
builder.Register(c => new B());
builder.Register(c => new C());

B

6条回答
  •  自闭症患者
    2020-12-05 06:23

    I was looking for a similar solution for registrations done as follows:

    builder.RegisterType().As();
    // and/or
    builder.RegisterType().Keyed(key);
    

    where IExoticTree and IMountainTree inherit from a common ITree interface.

    With those, the service type (e.g. registered interface) is different from the LimitType and hence, the proposed solution is not applicable.

    I got inspired by the accepted solution to manage these as well with the following code:

    IEnumerable instances = scope.ComponentRegistry.Registrations
                                                          .Where(r => typeof(ITree).IsAssignableFrom(r.Activator.LimitType))
                                                          .Select(r => r.Services.First())
                                                          .Select(s => scope.ResolveService(s) as ITree)
                                                          .Distinct();
    

    Hope it helps someone ^^

提交回复
热议问题