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 ...

Get Professional Test-Driven Development with C#: Developing Real World Applications with TDD now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.