Sunday, April 17, 2011

Why is DI important?

In the past week, I was asked by this question. Most people use OO strategy to write their codes. Each class or object has its encapsulated private data member and methods. They do try to separate business logic clear and narrow down only the jobs the class cares. What is Dependency Injection(DI) and why do we use DI?

I asked a similar question to another senior developer, "where do you use DI?" He told me that he only uses it in unit test as mocked objects to avoid real access to database. That's very common in unit tests. However, that's not enough. Actually DI is a very important concept and should be a common practice in our daily coding.

I recalled my previous projects and went through the pattern I used. Here is my further explanation. Take the following codes as example:

public class MyDataReader {
...

public bool ReadData() {
var dbService = new MyDbService();
....
var data = dbService.GetObject();
....
}
}


The question code is the place where dbService object is created. How many times we have seen this type creation in our classes. The class MyDataReader has dependency on MyDbService class. In other words, it knows what db service class to use. Does MyDataReader class need to know that? Isn't that better if separate this specific logic from MyDataReaer?

Now look at the following updated codes:

public class MyDataReader {
...

public bool ReadData() {
var dbService = DIContainer.GetInstance<IDBService>();
....
var data = dbService.GetObject();
....
}
}


The only change is that MyDataReader does not have knowledge of what concrete db service is any more. It passes the job to a container class to get an instance of db service which implements the interface of IDBService. If you make changes in the container, then the instance you want to be used will be able to inject to MyDataReader class. You don't need to change MyDataReader class at all. This is a typical case of DI.

By implement DI pattern, your class will be truly OO. Less coupling is a critical principle of OO. You should always to use DI container as much as possible to separate the relationship between concrete classes. To do DI coding, you do need to create your container class and following your pattern to register the relationship between interface and class.

Fortunately, there are many great DI patterns available. I wrote blogs on Structure Map and MEF. Those are great DI Containers. For sure, you need to learn those patterns and ways they require, but I think it is worthwhile. Write better and clean codes will benefit you and your applications.

0 comments: