2009-08-06 9 views
0

反射で城内のインターフェイスを解決しようとすると、小さな問題が発生しました。城ウィンザー反射によるインターフェイス解像度

私はインターフェイスIServiceを持っており、このようにそれを解決することができると言うことができます:

var service = wc.Resolve<IService>(); 

これは期待通りに動作しますが、私は反射によってメソッドを呼び出すようにしたいと、このようにそれを行うことができます。

MethodInfo method = typeof(WindsorContainer).GetMethod("Resolve",new Type[] {}); 
MethodInfo generic = method.MakeGenericMethod(typeof(IService)); 
var service = generic.Invoke(wc,new object[]{}); 

これも正常に動作します。ここで、リフレクションを使用してリロードするタイプを選択したいと考えてみましょう。その後、

Type selectedType = assembly.GetType("myProject.IService") 

そして、このようにそれを起動しよう:

MethodInfo method = typeof(WindsorContainer).GetMethod("Resolve",new Type[] {}); 
MethodInfo generic = method.MakeGenericMethod(selectedType); 
var service = generic.Invoke(wc,new object[]{}); 

私は城のエラーを取得:

"No component for supporting the service myProject.IService was found" 

selectedTypeのタイプが正しいように見えますが、問題があります。

私は解決方法を正しく呼び出すために何ができるか知っていますか?

BTW MakeGenericMethod(typeof(selectedType)はコンパイルされません。

ありがとうございます。

答えて

2

なぜあなたはMakeGenericMethodを必要としますか? Castle has a non-generic Resolve method

ちょうどcontainer.Resolve(selectedType)は機能しますか?

+0

container.Resolve(selectedType)は同じエラーを生成します。非汎用メソッドについてのポインタをありがとう。 – jheppinstall

1

IServiceのコンポーネントを登録しましたか?これは私のためにちょうどうまく動作します:

using System; 
using Castle.Windsor; 
using NUnit.Framework; 

namespace WindsorInitConfig { 
    [TestFixture] 
    public class ReflectionInvocationTests { 
     public interface IService {} 

     public class Service: IService {} 

     [Test] 
     public void CallReflection() { 
      var container = new WindsorContainer(); 
      container.AddComponent<IService, Service>(); 

      var selectedType = Type.GetType("WindsorInitConfig.ReflectionInvocationTests+IService"); 
      var method = typeof(WindsorContainer).GetMethod("Resolve", new Type[] { }); 
      var generic = method.MakeGenericMethod(selectedType); 
      var service = generic.Invoke(container, new object[] { }); 
      Assert.IsInstanceOfType(typeof(IService), service); 
     } 
    } 
} 
+0

あなたの答えをありがとう、私は上記の動作を生成した.configファイルに登録されたコンポーネントを持っていた。最後に、私はAddComponentメソッドを使ってコンポーネントを追加しました。これはうまくいきましたが、オブジェクトをいくらか打ち負かしました。今私は文字列キーを使用して解決することができますが、コードではなく、設定に依存しています。 – jheppinstall

関連する問題