如何获得所有已注册的服务类型Autofac

问题描述:

我有一个Autofac容器中,我想能够检索所有注册的服务类型(而不是实现类型,但它们的类型被注册为)。如何获得所有已注册的服务类型Autofac

?我怎样才能从IComponentContext这一信息?

您可以使用此:

var services = 
    context.ComponentRegistry.Registrations.SelectMany(x => x.Services) 
      .OfType<IServiceWithType>() 
      .Select(x => x.ServiceType); 
+0

只好选择更改为凡为了找回一个IEnumerable的服务。变种服务= context.ComponentRegistry.Registrations.SelectMany(X => x.Services) .OfType () 。凡(X => x.ServiceType); – NovaJoe 2013-12-06 17:57:02

+1

@NovaJoe:这是不可能的:你的代码将无法编译,因为'ServiceType'不是'bool'。而且它不会做太多的感觉反正... – 2013-12-06 18:26:54

+0

对不起,忘了声明的一部分:VAR的服务= container.ComponentRegistry.Registrations.SelectMany(X => x.Services).OfType ()在哪里。 (x => x.ServiceType == serviceType);请注意特定服务类型的相等性检查。此外,我有容器,而不是上下文,这是一个AutoFac IContainer。 – NovaJoe 2013-12-07 21:17:46

我如何解决它

var alldb = (from r in MasterDataFactory.Container.ComponentRegistry.Registrations 
       let s = r.Services.Where(i => i is KeyedService).Select(i => i as KeyedService).FirstOrDefault() 
       where s!=null && s.ServiceType==typeof(ISomeInterface) 
       select s).ToList();