2012-12-27 11 views
5

IComponentContextから特定のインタフェースを実装する登録済みTypeのリストを取得する必要があります。Autofacのインタフェースの登録済み実装をすべて取得

タイプの実際のインスタンスを望んでいませんが、のインスタンスを取得するTypeのリストがあります。

このリストを使用して、メッセージバス上のサブスクリプションを生成します。

登録されたインターフェイスの実装をすべてAutofacで取得するにはどうすればよいですか?

+1

Reflectionを使用して、アセンブリ内のすべての型を反復処理し、それらが 'IComponentContext'を実装しているかどうか確認しましたか? [C#3.5でインターフェイスを実装するすべての型を取得する](http://stackoverflow.com/questions/26733/getting-all-types-that-implement-an-interface-with-c-sharp-3-5)を参照してください。 –

+0

@NikolayKhilそれは問題ではありません。私はコンテキストを見て、登録されたタイプを見つける必要があります。これはAutofac固有の質問です。 –

答えて

13

私はこれを考え出した -

var types = scope.ComponentRegistry.Registrations 
    .SelectMany(r => r.Services.OfType<IServiceWithType>(), (r, s) => new { r, s }) 
    .Where(rs => rs.s.ServiceType.Implements<T>()) 
    .Select(rs => rs.r.Activator.LimitType); 
+0

ServiceTypeにImplementsメソッドがありません! –

+1

それでも最新のAutofacで動作します。 –

0

でAutoFac 3.5.2(この記事に基づいて:http://bendetat.com/autofac-get-registration-types.html

が最初にこの機能を実装します。

using Autofac; 
    using Autofac.Core; 
    using Autofac.Core.Activators.Reflection; 
    ... 

     private static IEnumerable<Type> GetImplementingTypes<T>(ILifetimeScope scope) 
     { 
      //base on http://bendetat.com/autofac-get-registration-types.html article 

      return scope.ComponentRegistry 
       .RegistrationsFor(new TypedService(typeof(T))) 
       .Select(x => x.Activator) 
       .OfType<ReflectionActivator>() 
       .Select(x => x.LimitType); 
     } 

その後、仮定あなたは持っていますbuilder

var container = builder.Build(); 
using (var scope = container.BeginLifetimeScope()) 
{ 
    var types = GetImplementingTypes<T>(scope); 
} 
関連する問題