views:

345

answers:

2

Hi all,

I have encountered a small problem when trying to resolve an interface in castle using reflection.

Lets say I have an interface IService, and can resolve it like this:

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

This works as expected, but I want to call the method through reflection and can do so like this:

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

This also works fine. Now lets imagine I want to select the type to be reloved using reflection.

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

And then try to invoke it like this:

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

I get a Castle error:

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

The Type of selectedType appears to be correct, but there is a problem.

Does anyone know what I can do to invoke the resolve method correctly?

BTW MakeGenericMethod(typeof(selectedType) does not compile.

Thanks in advance

+1  A: 

Why do you even need MakeGenericMethod? Castle has a non-generic Resolve method

Does just container.Resolve(selectedType) work?

George Mauer
container.Resolve(selectedType) produces the same error. Thanks for the pointer about the non generic method.
jheppinstall
+1  A: 

Did you register a component for IService? This works just fine for me:

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);
        }
    }
}
Mauricio Scheffer
Thanks for your answer, I had a component registered in a .config file, which produced the behaviour above. In the end I added a component using the AddComponent method, which did work, but defeated the object somewhat. Now I can resolve using the String Key, but have a dependency in code, not in the config.
jheppinstall