O'Reilly logo

Professional Test-Driven Development with C#: Developing Real World Applications with TDD by Jeff McWherter, James Bender

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

THE DEPENDENCY INJECTION PATTERN

In a traditional application designed with OOP, you create service and entity classes to abstract real-world processes and entities. An application is then composed of these various service and entity classes. This composition creates dependencies between the classes in your applications. The most obvious way to express and manage these dependencies is to statically create them in code as part of your class's initialization process. (This example can be found in the Before folder in the downloaded code sample on www.wrox.com.)

images
public class BusinessService
{
    private readonly string _databaseConnectionString =
ConfigurationManager.ConnectionStrings[“MyConnectionString”].ConnectionString;
    private readonly string _webServiceAddress =
        ConfigurationManager.AppSettings["MyWebServiceAddress"];
    private readonly LoggingDataSink _loggingDataSink;
          
    private DataAccessComponent _dataAccessComponent;
    private WebServiceProxy _webServiceProxy;
    private LoggingComponent _loggingComponent;
          
    public BusinessService()
    {
        _loggingDataSink = new LoggingDataSink();
        _loggingComponent = new LoggingComponent(_loggingDataSink);
        _webServiceProxy = new WebServiceProxy(_webServiceAddress);
        _dataAccessComponent = new DataAccessComponent(_databaseConnectionString);
    }
}

BusinessService.cs

Several problems occur when this method is used to handle dependencies between classes. The most ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required