text
stringlengths
0
13.4k
public interface IGreetingProvider
{
string GetGreeting();
}
public interface IGreetingWriter
{
void WriteGreeting(string greeting);
}
The Greeting class depends on both IGreetingProvider and IGreetingWriter, but it is not responsible for
creating instances of either. Instead it requires them in its constructor. Whatever creates an instance of Greeting
must provide those two dependencies. We can call that "injecting" the dependencies.
Because dependencies are provided to the class in its constructor, this is also called "constructor injection."
A few common conventions:
The constructor saves the dependencies as private fields. As soon as the class is instantiated, those
dependencies are available to all other non-static methods of the class.
The private fields are readonly. Once they are set in the constructor they cannot be changed. This indicates
that those fields should not (and cannot) be modified outside of the constructor. That further ensures that
those dependencies will be available for the lifetime of the class.
The dependencies are interfaces. This is not strictly necessary, but is common because it makes it easier to
substitute one implementation of the dependency with another. It also allows providing a mocked version of
the interface for unit testing purposes.
Section 26.3: Why We Use Dependency Injection Containers
(IoC Containers)
Dependency injection means writing classes so that they do not control their dependencies - instead, their
dependencies are provided to them ("injected.")
This is not the same thing as using a dependency injection framework (often called a "DI container", "IoC container",
or just "container") like Castle Windsor, Autofac, SimpleInjector, Ninject, Unity, or others.
A container just makes dependency injection easier. For example, suppose you write a number of classes that rely
on dependency injection. One class depends on several interfaces, the classes that implement those interfaces
depend on other interfaces, and so on. Some depend on specific values. And just for fun, some of those classes
GoalKicker.com – .NET Framework Notes for Professionals
91
implement IDisposable and need to be disposed.
Each individual class is well-written and easy to test. But now there's a different problem: Creating an instance of a
class has become much more complicated. Suppose we're creating an instance of a CustomerService class. It has
dependencies and its dependencies have dependencies. Constructing an instance might look something like this:
public CustomerData GetCustomerData(string customerNumber)
{
var customerApiEndpoint = ConfigurationManager.AppSettings["customerApi:customerApiEndpoint"];
var logFilePath = ConfigurationManager.AppSettings["logwriter:logFilePath"];
var authConnectionString =
ConfigurationManager.ConnectionStrings["authorization"].ConnectionString;
using(var logWriter = new LogWriter(logFilePath ))
{
using(var customerApiClient = new CustomerApiClient(customerApiEndpoint))
{
var customerService = new CustomerService(
new SqlAuthorizationRepository(authorizationConnectionString, logWriter),
new CustomerDataRepository(customerApiClient, logWriter),
logWriter
);
// All this just to create an instance of CustomerService!
return customerService.GetCustomerData(string customerNumber);
}
}
}
You might wonder, why not put the whole giant construction in a separate function that just returns
CustomerService? One reason is that because the dependencies for each class are injected into it, a class isn't
responsible for knowing whether those dependencies are IDisposable or disposing them. It just uses them. So if a
we had a GetCustomerService() function that returned a fully-constructed CustomerService, that class might
contain a number of disposable resources and no way to access or dispose them.
And aside from disposing IDisposable, who wants to call a series of nested constructors like that, ever? That's a
short example. It could get much, much worse. Again, that doesn't mean that we wrote the classes the wrong way.