Thursday, July 25, 2013

Dependency Injection


http://msdn.microsoft.com/en-us/library/ff921152(v=pandp.20).aspx

 public class Program
    {
        static void Main(string[] args)
        {
            Customer customer1 = new Customer(new BasicLogger());
            Customer customer2 = new Customer(new AdvancedLogger());

            Console.ReadLine();
        }
    }

    public class Customer
    {
        public Customer(ILogger logger)
        {
            logger.WriteToLog("creating the customer");
        }
    }

    public interface ILogger
    {
        void WriteToLog(string text);
    }

    public class BasicLogger : ILogger
    {
        public void WriteToLog(string text)
        {
            Console.WriteLine(text);
        }
    }

    public class AdvancedLogger : ILogger
    {
        public void WriteToLog(string text)
        {
            Console.WriteLine("*** {0} ***", text);
        }
    }Problem
You have classes that have dependencies on services or components whose concrete type is specified at design time. In this example, ClassA has dependencies on ServiceA and ServiceB. Figure 1 illustrates this.
Ff921152.07e319ee-bf28-4695-a194-4ce8e467e90d(en-us,PandP.20).png

Figure 1 
ClassA has dependencies on ServiceA and ServiceB
This situation has the following constraints:
  • To replace or update the dependencies, you must change your classes' source code.
  • The concrete implementation of the dependencies must be available at compile time.
  • Your classes are difficult to test in isolation because they have a direct reference to their dependencies. This means that these dependencies cannot be replaced with stubs or mocks.
  • Your classes contain repetitive code for creating, locating, and managing their dependencies.

Forces

Any of the following conditions justifies using the solution described in this pattern:
  • You want to decouple your classes from their dependencies so that these dependencies can be replaced or updated with minimal or no changes to your classes' source code.
  • You want to be able to write classes that depend on classes whose concrete implementation is not known at compile time.
  • You want to be able to test your classes in isolation, without using the dependencies.
  • You want to decouple your classes from being responsible for locating and managing the lifetime of dependencies.

Solution

Do not instantiate the dependencies explicitly in your class. Instead, declaratively express dependencies in your class definition. Use a Builder object to obtain valid instances of your object's dependencies and pass them to your object during the object's creation and/or initialization. Figure 2 illustrates this.
Ff921152.81db980b-fa2d-4fe3-b6b6-f40995120159(en-us,PandP.20).png

Figure 2 
Conceptual view of the Dependency Injection pattern
Ff921152.note(en-us,PandP.20).gifNote:
Typically, you express dependencies on interfaces instead of concrete classes. This enables easy replacement of the dependency concrete implementation without modifying your classes' source code.
The following are the two main forms of dependency injection:
  • Constructor injection
  • Setter injection
In constructor injection, you use parameters of the object's constructor method to express dependencies and to have the builder inject it with its dependencies. In setter injection, the dependencies are expressed through setter properties that the builder uses to pass the dependencies to it during object initialization.

Implementation Using the Unity Application Block

The Dependency Injection pattern can be implemented in several ways. The Unity Application Block (Unity) provides a container that can be used for dependency injection. For more information about the Unity Application Block, see Unity Application Block.

Example

The NewsReaderPresenter class of the Stock Trader Reference Implementation (located at StockTraderRI.Modules.News\Article\NewsReaderPresenter.cs) uses constructor dependency injection to obtain a valid instance of a view that implements the INewsReaderView interface. The class definition is shown in the following code.
public class NewsReaderPresenter : INewsReaderPresenter
{
    private readonly INewsReaderView view;

    public NewsReaderPresenter(INewsReaderView view)
    {
        this.view = view;
    }

    public INewsReaderView View
    {
        get { return this.view; }
    }

    public void SetNewsArticle(NewsArticle article)
    {
        this.view.Model = article;
    }
}
Because the NewsReaderPresenter class uses dependency injection to obtain its dependencies, its dependencies can be replaced with mock implementations when testing. The following test methods, taken from the fixture file StockTraderRI.Modules.News.Tests\Article\NewsReaderPresenterFixture.cs, show how theNewsReaderPresenter class can be tested in isolation using mock implementations to replace the classes' dependencies and verify behavior.
[TestMethod]
public void SetNewsArticlesSetsViewModel()
{
    var view = new MockNewsReaderView();

    var presenter = new NewsReaderPresenter(view);

    NewsArticle article = new NewsArticle() { Title = "My Title", Body = "My Body" };
    presenter.SetNewsArticle(article);

    Assert.AreSame(article, view.Model);
}

Liabilities

The dependency injection pattern has the following liabilities:
  • There are more solution elements to manage.
  • You have to ensure that, before initializing an object, the dependency injection framework can resolve the dependencies that are required by the object.
  • There is added complexity to the source code; therefore, it is harder to understand.

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.

No comments:

Post a Comment