城堡温莎通过反射接口分辨率

时间:2009-08-06 21:39:34

标签: reflection castle-windsor

尝试使用反射解决城堡中的界面时遇到了一个小问题。

假设我有一个接口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[]{});

我收到了一个Castle错误:

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

selectedType的类型似乎是正确的,但是有问题。

有谁知道我可以做些什么来正确调用resolve方法?

BTW MakeGenericMethod(typeof(selectedType)无法编译。

提前致谢

2 个答案:

答案 0 :(得分:2)

为什么你甚至需要MakeGenericMethod? Castle has a non-generic Resolve method

container.Resolve(selectedType)是否有效?

答案 1 :(得分: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);
        }
    }
}