获取实现特定接口的所有已注册对象的列表

kas*_*rhj 14 autofac

考虑以下

builder.Register(c => new A());
builder.Register(c => new B());
builder.Register(c => new C());
Run Code Online (Sandbox Code Playgroud)

B并且C都是ISomeInterface.

我现在想要获得IEnumerable所有已实现的注册对象ISomeInterface.

如何在Autofac中实现这一目标?

Tim*_*art 25

如果你有

container.Register(c => new A()).As<ISomeInterface>();
container.Register(c => new B()).As<ISomeInterface>();
Run Code Online (Sandbox Code Playgroud)

然后当你这样做

var classes = container.Resolve<IEnumerable<ISomeInterface>>();
Run Code Online (Sandbox Code Playgroud)

您将获得一个变量,它是ISomeInterface的列表,包含A和B.


cat*_*ier 23

试过这个,有效并且不依赖于生命周期:

使用Activator枚举类型

var types = con.ComponentRegistry.Registrations
     .Where(r => typeof(ISomeInterface).IsAssignableFrom(r.Activator.LimitType))
     .Select(r => r.Activator.LimitType);
Run Code Online (Sandbox Code Playgroud)

然后解决:

IEnumerable<ISomeInterface> lst = types.Select(t => con.Resolve(t) as ISomeInterface);
Run Code Online (Sandbox Code Playgroud)


kas*_*rhj 5

这是我如何做到的。

var l = Container.ComponentRegistry.Registrations
          .SelectMany(x => x.Services)
          .OfType<IServiceWithType>()
          .Where(x => 
                 x.ServiceType.GetInterface(typeof(ISomeInterface).Name) != null)
          .Select(c => (ISomeInterface) c.ServiceType);
Run Code Online (Sandbox Code Playgroud)