Search code examples
c#.netgenericscastle-windsor

Registering generic components in Windsor.Castle: difference in behavior between Type.GetType and typeof


I'm testing Windsor.Castle for the resolving of my generic components.

I'm configuring my container with lines like the following:

container.Register(Component.For(typeof(ICommand<,>)).ImplementedBy(Type.GetType("WCExp.Test.GetAllCommand`2")).Named("GetAllCommand"));
container.Register(Component.For(typeof(ICommand<,>)).ImplementedBy(typeof(WindsorCastleExperiments.Implementations.GetAllCommand<,>)).Named("GetAllCommandOriginal"));

As you can see ImplementedBy is provided a Type, either through Type.GetType() or through typeof().

Now while I was testing, I noticed that sometimes the registrated service was not the implementing class, but the interface .

Error message:Error creating instance ICommand... is abstract. ( left out full type string)

Is it possible that when using Type.GetType() can sometimes return a interface for a given type string, even if the given type string is the class type definition?

Thus can

Type.GetType("WCExp.Test.GetAllCommand`2")

return the interface ICommand<,>...?

This was happening for the classes that were residing in a dependent assembly. For classes in the same assembly as I was configuring this problem didn't present itself (yet?)

Full sources: https://github.com/schwarzie2478/WindsorCastleExperiments


Solution

  • I solved my problem. In the end it had nothing to do with Castle. ( But Castle allows it to happen ): )

    Type.GetType expects a type string that includes the assemblyName for types that exist outside of the currently running assembly.

    But because I never checked to see what this function returned, I didn't know the registration was happening against a null value, which Castle allows, but then the interface is registered as the service instead of an implementation as I expected...