Saturday, May 11, 2013

C# Covariance With Castle Windsor

Purpose

  • Show Simple Examples on how to use covariance in C# .net4 and above
  • Show Simple Examples on how to use with Castle Windsor container
  • Describe what Covariance is and how it might be used.

Code


Covariance Interface

A covariance interface is simply defined with a Type T precluded by the out keyword. The interface can then be used to access more derived types.  That is the key and what covariance gives you.

This can be implemented as follows:

Covariant Registration and Resolution using Castle Windsor


In the registration we have declared the type of the covariant interface to be of a base type(in the For<>). In the implemented declaration we reference the derived type. When ResolveAll is called we use the base type, that was specified in the For<>, and get a covariant array with all our types.


Covariant Registration and Resolution by convention using Castle Windsor


In the registration we have declared that all Classes in the assembly that are of a specific type(BasedOn(typeOf(someType)), should resolve to a service using an IEnumerable with the Base type(Select(new []{tyoeOf(someBaseType)}. When ResolveAll is called we use the base type, that was specified in the For<>, and get a covariant array with all classes in the assembly that are based on our covariant interface.

Covariance Definition


MSDN defines Covariance as Covariance allows interface methods to have more derived return types than that defined by the generic type parameters.[1] What this provides is a mechanism to use generics in a polymorphic way. Without using this technique one might get into a situation where you have to continually cast and/or use non-generic objects. A situation where this might be useful is when a generic service is called on several unrelated types. An example is a database extract/loader service, in which we need to load several unrelated types and return the results. Here is the complete example that can be run as a test:

Additional information regarding syntax rules and other examples can be found on Eric Lippert's Blog[2]

References: [1] - MSDN definition
References: [2] - Eric Lippert's Blog