Dependency Injection in .NET with examples?

Here’s a common example. You need to log in your application. But, at design time, you’re not sure if the client wants to log to a database, files, or the event log.

So, you want to use DI to defer that choice to one that can be configured by the client.

This is some pseudocode (roughly based on Unity):

You create a logging interface:

public interface ILog
{
  void Log(string text);
}

then use this interface in your classes

public class SomeClass
{
  [Dependency]
  public ILog Log {get;set;}
}

inject those dependencies at runtime

public class SomeClassFactory
{
  public SomeClass Create()
  {
    var result = new SomeClass();
    DependencyInjector.Inject(result);
    return result;
  }
}

and the instance is configured in app.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name ="unity"
             type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,
              Microsoft.Practices.Unity.Configuration"/>
  </configSections>
  <unity>
    <typeAliases>
      <typeAlias alias="singleton"
                 type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager,Microsoft.Practices.Unity" />
    </typeAliases>
    <containers>
      <container>
        <types>
          <type type="MyAssembly.ILog,MyAssembly"
                mapTo="MyImplementations.SqlLog, MyImplementations">
            <lifetime type="singleton"/>
          </type>
        </types>
      </container>
    </containers>
  </unity>
</configuration>

Now if you want to change the type of logger, you just go into the configuration and specify another type.

Leave a Comment