Injecting instance via configuration

Mar 29, 2012 at 2: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 4:22 AM
Edited Mar 30, 2012 at 4: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 1:38 PM

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