A colleague of mine just had an interesting problem. Assume a generic class

namespace MyNamespace {   

public class MyGeneric<T>
        private string name;  

        public String Name {
            get { return name; }
            set { name = value; }
        }
        ...
    }
}

Now if you want to create an object of this type via spring, you just specify the following in the app context (assuming that this class resides inside MyAssembly.dll):

<object id="myGeneric"
        type="MyNamespace.MyGeneric<int>, MyAssembly">
    <property name="Name" value="My Generic Class with int"/>
</object>

Note that the xml notation for less-than in MyNamespace.MyGeneric<int is not a typo: spring really requires this to be specified this way. Now, suppose that you don’t want to use an int but a custom type as the generic type, let’s say

namespace MyOtherNamespace {
    public class MyClass {
        ...
    }
}

If this type resides in the same assembly, you can just say

<object id="myOtherGeneric"
        type="MyNamespace.MyGeneric<MyOtherNamespace.MyClass>, MyAssembly">
    <property name="Name" value="My Generic Class with int"/>
</object>

However, if the class of the generic type sits in another assembly, you have to use a workaround. Just adding the assembly after the type won’t work, as the comma is used as the delimiter for multiple generic type arguments. Luckily, spring supports something called a TypeAlias, which, as the name implies, let’s us define an alias for a type. First define the alias

<typeAliases>
    <alias name="MyClass" type="MyOtherNameSpace.MyClass, MyOtherAssembly" />
</typAliases>

With this type alias defined, we can now define the object as

<object id="myOtherGeneric"
        type="MyNamespace.MyGeneric<MyClass>, MyAssembly">
    <property name="Name" value="My Generic Class with int"/>
</object>
Advertisements