Injecting instance via configuration

Mar 29, 2012 at 3:55 AM

I have a library that makes available a client via a singleton:

IClient client = Client.Instance;

In code I can easily register this with a container:


Is there an easy out-of-the-box way to do this with an Xml configuration file?


Mar 30, 2012 at 5:22 AM
Edited Mar 30, 2012 at 5:26 AM

The answer is yes and no.  You can configure using the XML configuration file but you will also need to use a TypeConverter.

First you can configure the container using the <instance> tag in the configuration file:

 <unity xmlns="">

    <namespace name="MyApp"/>
    <assembly  name="MyApp"/>

      <instance type="IClient" typeConverter="ClientInstanceConverter" />    


Next create a TypeConverter to actually "create" the singleton instance:

public class ClientInstanceConverter : System.ComponentModel.TypeConverter
    public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        return Client.Instance;

With that in place you should be able to resolve the IClient interface:

var container = new UnityContainer().LoadConfiguration();

var client1 = container.Resolve<IClient>();
var client2 = container.Resolve<IClient>();

Debug.Assert(client1 == client2);

Randy Levy
Enterprise Library support engineer 

Mar 30, 2012 at 2:38 PM

Thanks Randy - thats pretty much what I had guessed, but good to see how to write a simple TypeConverter.