Tuesday, April 23, 2013

Practical Dependency Injection


Practical Dependency Injection 101

by EFVINCENT on 05/27/2011
In this post we take a look at dependency injection (DI). Target audience is competent .NET developers, C# specifically (but VB’ers who read C# can benefit just as much), who’ve heard of DI but haven’t gotten around to figuring out how it fits in their day to day.

What is Dependency Injection

The first question that we need to address is: What is it that DI does for us? What problem is being solved? DI is about coupling; the degree to which program unit refers to other units. In .NET the units we’re typically worried about are classes, interfaces, components, and assemblies. Dependency injection facilitates reduction these interdependencies. Are DI patterns a silver bullet? Of course not. You can always write bad code regardless of patterns. That being said, if you’re already writing decent code and have good fundamentals, but are not using DI patterns, you’ve got the opportunity to take a leap forward.
How does DI reduce help reduce coupling? The easiest way to describe it is by diving directly into an example.

Example Scenario

We’ll work on a hypothetical in-house app where the Windows AD authenticates employees, and their Windows username is used to index a database with Employee information. It’s pretty common to see stuff like this happening in-house with line of business applications.
The example uses a provider pattern – all the data access will go through a data access provider, allowing us to build a simple provider that stores records in memory during this, our prototype phase. Theoretically we’d replace this as development continued with a provider that leverages persistent storage later.
Here’s the base level example program with no consideration for dependency injection:
01.class Program {
02.static void Main(string[] args) {
03. 
04.// ** Without using an DI Container approach **
05. 
06.// Create a new provider aka data access layer
07.var dal = new DevDataProvider();
08. 
09.// New up an employee that's supposed to represent the currently logged in user
10.var e = new Employee() {
11.WindowsUsername = "thanos\\efvincent",
12.EmployeeId = "0001",
13.FName = "Eric",
14.LName = "Vincent"
15.};
16. 
17.// Add it to the data access layer
18.dal.AddEmployee(e);
19. 
20.// See if the dal can find the current user
21.e = dal.GetCurrentEmployee();
22. 
23.Console.WriteLine(
24."Current logged in person is: {0}", e == null "unknown" : e.FName);
25. 
26.// End
27.Console.Write("Press any key...");
28.Console.ReadKey(true);
29. 
30.}
31.}
32. 
33.public class DevDataProvider {
34.private static readonly List<Employee> EmployeeStore = new List<Employee>();
35. 
36.public Employee GetCurrentEmployee() {
37.var emp = EmployeeStore.FirstOrDefault(
38.e => e.WindowsUsername.Equals(GetCurrentUserName(), StringComparison.OrdinalIgnoreCase));
39.return emp;
40.}
41. 
42.public void AddEmployee(Employee e) {
43.EmployeeStore.Add(e);
44.}
45. 
46.public IQueryable<Employee> Employees() {
47.return EmployeeStore.AsQueryable();
48.}
49. 
50.private static string GetCurrentUserName() {
51.var wu = WindowsIdentity.GetCurrent();
52.return wu == null string.Empty : wu.Name;
53.}
54.}
55. 
56.public class Employee {
57.public string WindowsUsername { getset; }
58.public string EmployeeId { getset; }
59.public string FName { getset; }
60.public string LName { getset; }
61.}
In Main() we new up the data access layer, create a new employee, and add it to our store using the data access layer. At line 21 we ask the data access layer to retrieve the employee record for the currently logged in user. Looks pretty typical, so how can IoC help? Let’s look at the coupling here – what classes are dependent on what other classes?
image
Our main program depends on the DevDataProvider class, and that depends on System.Security to find the Windows username of the currently logged in user. Asking the data access layer to determine the currently logged in user isn’t the best idea, but this is blog post code created to check out dependency injection, so deal with that for the moment.
Why are these dependencies undesirable? First consider how flexible this software is. Or rather, inflexible. We created a “quick” DevDataProvider that stores stuff in a static list. As we continue to build a system, we’d have to refer to DevDataProvider from more and more classes, creating a brittle, tightly coupled system. Replacing DevDataProvider becomes more of a maintenance problem.
Next think about testability. In real life there are unit tests (there should be anyway). One reason why people find excuses not to unit test is because their code is difficult to test. In this example, if we want to test DevDataProvider.GetCurrentEmployee() we have to consider that under the covers it’s calling the Windows API to get the current username. This makes that method harder to than it needs to be.

Step One – Leveraging Interfaces

In this version, we’ve factored out an interface called IDataProvider, and one called IIdentService. The IDataProvider should be pretty obvious – but IIdentService? The idea here is to decouple from the Windows API itself. A developer should understand everywhere that the application makes contact with any external modules, including the operating system, and then consider what the repercussions of that contact are. In this example, coupling to the Windows API to get then logged in username so directly is undesirable. We want to use a service that would supply us with credentials. That way if we’re testing, we can create a fake service that provides a predictable answer, and is therefore easier to test.
Coding to an interface also allows us to radically change the behavior of the service without having to alter its dependencies. If we move to a ASP.NET environment for example, we won’t want to use the current Windows Identity, we may want to use user information from the http context.
01.// Interface defining an identity service
02.public interface IIdentService {
03.string GetCurrentUserName();
04.}
05. 
06.// Implementation of an identity service that returns the current
07.// logged in windows username
08.public class WindowsIdentService : IIdentService {
09.public string GetCurrentUserName() {
10.var wu = WindowsIdentity.GetCurrent();
11.return wu == null string.Empty : wu.Name;
12.}
13.}
14. 
15.// Interface defining a data provider service
16.public interface IDataProvider {
17.Employee GetCurrentEmployee();
18.void AddEmployee(Employee e);
19.IQueryable<Employee> Employees();
20.}
21. 
22.// Our development data provider now implements the interface
23.public class DevDataProvider : IDataProvider {
24.private readonly IIdentService _identService;
25.private static readonly List<Employee> EmployeeStore = new List<Employee>();
26. 
27.public DevDataProvider(IIdentService identService) {
28.if (identService == nullthrow new ArgumentNullException("identService");
29._identService = identService;
30.}
31. 
32.public Employee GetCurrentEmployee() {
33.var emp = EmployeeStore.FirstOrDefault(
34.e => e.WindowsUsername.Equals(
35._identService.GetCurrentUserName(),
36.StringComparison.OrdinalIgnoreCase));
37.return emp;
38.}
39. 
40.public void AddEmployee(Employee e) {
41.EmployeeStore.Add(e);
42.}
43. 
44.public IQueryable<Employee> Employees() {
45.return EmployeeStore.AsQueryable();
46.}
47.}
We’re part of the way to where we need to be. Altering DevDataProvider to depend on the IIdentService interface frees it from a hard dependency on a particular identity implementation. The downside is we’ve made creation of the DevDataProvider a bit more complex, as we need to supply the new instance with an IIdentityService instance.
1.// Create a new ident service, required for the DAL
2.IIdentService identSvc = new WindowsIdentService();
3. 
4.// Create a new DAL
5.IDataProvider dal = new DevDataProvider(identSvc);
The DevDataProvider now takes a constructor parameter of type IIdentService. This is where the injection in dependency injection comes from. DevDataProvider has a dependency, but instead of hard coding it into the definition of DevDataProvider, we inject it. There are different ways of injecting dependencies, but constructor injection is very popular and works well in many, or even most cases.
The complexity of constructing instances increases when we add a simple logging service which logs information or errors messages.
01.// Interface defining a logging service
02.public interface ILogService {
03.void LogInfo(string msg, params object[] args);
04.void LogError(string msg, params object[] args);
05.}
06. 
07.// Implementation of a console logging service
08.public class ConsoleLogger : ILogService {
09.public void LogInfo(string msg, params object[] args) {
10.Console.WriteLine(
11."{0} INFO: {1}", DateTime.Now,
12.string.Format(msg, args));
13.}
14. 
15.public void LogError(string msg, params object[] args) {
16.Console.WriteLine(
17."{0} ERROR: {1}", DateTime.Now,
18.string.Format(msg, args));
19.}
20.}
The ILogService is implemented by a simple console logger. Now both the WindowsIdentService and the DevDataProvider can leverage the logger. They’re both modified to have ILogService instance injected via their respective constructors.
01.// Implementation of an identity service that returns the current
02.// logged in windows username
03.public class WindowsIdentService : IIdentService {
04.private readonly ILogService _logSvc;
05. 
06.public WindowsIdentService(ILogService logSvc) {
07.if (logSvc == nullthrow new ArgumentNullException("logSvc");
08._logSvc = logSvc;
09.}
10. 
11.public string GetCurrentUserName() {
12.var wu = WindowsIdentity.GetCurrent();
13.var un = wu == null string.Empty : wu.Name;
14._logSvc.LogInfo("Identified current user as: {0}", un);
15.return un;
16.}
17.}
18. 
19.// Our development data provider now implements the interface
20.public class DevDataProvider : IDataProvider {
21.private readonly IIdentService _identService;
22.private readonly ILogService _logSvc;
23.private static readonly List<Employee> EmployeeStore = new List<Employee>();
24. 
25.public DevDataProvider(IIdentService identService, ILogService logSvc) {
26.if (identService == nullthrow new ArgumentNullException("identService");
27.if (logSvc == nullthrow new ArgumentNullException("logSvc");
28._identService = identService;
29._logSvc = logSvc;
30.}
31. 
32.public Employee GetCurrentEmployee() {
33.var un = _identService.GetCurrentUserName();
34.var emp = EmployeeStore.FirstOrDefault(
35.e => e.WindowsUsername.Equals(un,
36.StringComparison.OrdinalIgnoreCase));
37.if (emp == null) _logSvc.LogInfo("Current employee {0} not found", un);
38.return emp;
39.}
40. 
41.public void AddEmployee(Employee e) {
42.EmployeeStore.Add(e);
43._logSvc.LogInfo("Added employee with id {0}", e.EmployeeId);
44.}
45. 
46.public IQueryable<Employee> Employees() {
47.return EmployeeStore.AsQueryable();
48.}
49.}
Now the services are getting more robust and they’re not tightly coupled to each other, they refer only to interfaces of the services they depend on. Main() however, where construction is going on, is getting messy.
01.static void Main(string[] args) {
02. 
03.// ** Without using an DI Container approach **
04. 
05.// Create a new logging service, required for uh.. everything
06.ILogService consoleLog = new ConsoleLogger();
07. 
08.// Create a new ident service, required for the DAL
09.IIdentService identSvc = new WindowsIdentService(consoleLog);
10. 
11.// Create a new DAL
12.IDataProvider dal = new DevDataProvider(identSvc, consoleLog);
Finally we’re at the point where we can see the benefit of an dependency injection container. One thing about DI containers is that they’re already written. Several mature, robust, open-source DI containers exist. We’ll use AutoFac, because that’s what I’ve been using lately. We include AutoFac using NuGet.
01.// Create a singleton dependency injection container
02.private static readonly IContainer Container = ConfigureContainer();
03. 
04.// Configure the container
05.static IContainer ConfigureContainer() {
06.// This is how AutoFac works. Other DI containers have similar
07.// mechanisms for configuring the container
08.var bld = new ContainerBuilder();
09. 
10.// Register the types that implement the interfaces that are required
11.// for injection. Note that we have robust control over lifetime, in
12.// this case ILogService and IIdentService will be singletons, and
13.// IDataProvider will provide a new instance each time it's requested
14.bld.RegisterType<ConsoleLogger>().As<ILogService>().SingleInstance();
15.bld.RegisterType<WindowsIdentService>().As<IIdentService>().SingleInstance();
16.bld.RegisterType<DevDataProvider>().As<IDataProvider>();
17.return bld.Build();
18.}
19. 
20.static void Main(string[] args) {
21. 
22.// ** Using an IoC Container approach **
23.var dal = Container.Resolve<IDataProvider>();
We’ve created a static instance of IContainer (an AutoFac DI container). When we start the app we configure the container, which fundamentally consists of mapping the interfaces to concrete types that will be injected. For example, line 14 specifies that when there’s a need for an instance of ILogService, we will create an instance of ConsoleLogger. It further says that the DI container should use a SingleInstance() of ConsoleLogger. This has the effect of making ConsoleLogger a singleton. In our example, both the WindowsIdentService and the DevDataProvider will be handed the same instance of ConsoleLogger.
The magic happens when we call Container.Resolve<IDataProvider>(). The container determines what concrete class to create, and it looks for any dependencies in the constructor. It will see that to build a DevDataProvider, it needs an ILogService and an IWindowsIdentService, it will recursively resolve those as well.
These are the basics of dependency injection. Even in this simple example, it should be obvious that the components and classes that we can create can be designed with very low coupling and cohesion using this technique. There are anti-patterns for using DI as well. You should endeavor to practice this technique, do research and learn the most effective uses; there’s plenty of material out there.
I hope this example was helpful. Next post I’ll extend this sample by looking at testing, and mock objects, and how DI injection can make testing far easier.
Source code samples can be found at this bitbucket repository.
Update: Follow up post – Dependency Injection, Testing, and Mocking
{ 1 trackback }
A Taste of Dependency Injection, Testing, and Mocking
06/02/2011 at 1:46 pm
{ 4 comments… read them below or add one }
 Sivakumar M 12/19/2011 at 1:07 am
Thanks for your post. It is a simple good practical example for anyone to relate to their daily work.
 Kamal 12/07/2012 at 1:20 pm
Its a simple and easy to understand article. Well explained!!!!
 Gary 01/31/2013 at 4:27 pm
good job thanks!
 Martix 03/20/2013 at 5:03 pm
nice and clean article, thanks ;)
Leave a Comment