This is the start of a series of posts that I’ll be doing on design patterns and best practices; it involves the use of common development concepts that I find a core part of development. If your interested in following, they will be under the category ‘Patterns and Practices’.
One of the most common patterns seen in ASP.NET MVC is dependency injection (otherwise known as Inversion of Control). Why? It loosely couples the parts of the application and really emphasizes the ability to unit test the separate layers of your application. Why is unit testing important? Unit Testing, while it may add more time to your development, it allows developers, testers and the client to feel more confident that their code is doing what it is supposed to do.
So what exactly is dependency injection? Many of us use patterns without even knowing that we are doing it, so this may sound familiar. It’s actually pretty straightforward, using an instance of one class, it calls an instance of another class, but not by a concrete implementation, but rather by interface. In essence, dependency injection, aims to reduce the amount of boilerplate wiring and infrastructure code that you must write and implement one of the core design principles, code to an interface not a implementation.
Here’s a simple example, the AccountService has to get a Account. It looks like this:
public class AccountService
{
private IAccountRepository _accountRepository;
public AccountService(IAccountRepository accountRepo)
{
_accountRepository = accountRepo;
}
public Account GetAccount(int accountId)
{
return _accountRepository.GetAccountById(accountId);
}
}
When we need the AccountRepository, we ask the dependency container to get it for us the instance based on what it’s mapped too. Why does this benefit developers? It’s good because the AccountService doesn’t know or care about it gets an Account. You can stub out what the methods and properties on a fake IAccountRepository might return, and test just the AccountService. You can also use this to change the implementation of the IAccountRepository on the fly based on the type of storage you may be using. Coupled with a framework such as Ninject, using dependency injection is a powerful pattern that should be used more often. In one of my following posts I’ll go into using an example of using Ninject and a basic tutorial.
Article source: http://robbiemadan.com/2012/05/09/patterns-and-practices-dependency-injection-101/