Thursday, January 12, 2012

Where We Need Dependency Injection

Recently I was working with a .Net project which uses Entity Framework .It has a layered architecture where we can find following separate layers.

 Service layer (Eg: Order Services)
 Domain Layer (Eg: Domain entities like book,Order)
 Infrastructure Layer (Repositories, DBContexts,Unit of work pattern Impl) 
 MVC3 Client (Presentation Layer)

 In my case Service methods are called in controller classes in MVC3 client package(according to the mvc pattern). MVC3 client package and Service layer are implemented by two developers .In this case MVC3 client project does not know much details about Service package and all he knows about the service package is that he can get some services by passing values to the service method.

 Eg: Lets say in service package we are having BookService class which is offering borrow book functionality. Then from the controller’s point of view what he wants to do is borrow a book by just passing the book id. Simply the controller doesnot want to know the underline functionality of Bookservice class (DBcontext,repositories,unitofworks)

 But according to the implementation of the BookService class it has only one constructor which has all its dependencies which are unknown by controller (MVC3 client project). Then when it comes to instance creation of BookService class we may end up with big issue. To solve this issue we need to inject dependencies of BookService by using a third party which knows about object creation of BookService class. This is called contractor dependency injection .Actually what controller wants to know is how to use bookservice object instead of knowing how to create BookService object.

Following are the structure of CSharp classes  I was explaining above.

  
public class BookService : IBookService
{
       public IBookRepository _bookrepository;
       public IUnitOfWork _unitOfWork;
    public BookService(IBookRepository bookRepository,IUnitOfWork unitOfWork)
    {
         _bookrepository = bookRepository;
         _unitOfWork = unitOfWork;
     }
    public Book BorrowBook(int bookId)
   {
         //Logic Goes Here
    }
}

Public class BookController
{
   IBookService _bookService;
    public BookController(IBookService bookService)
   {
           _bookService = bookService;
    }

   //Borrow book HTTP POST 
   public void BorrowBook(int bookId)
   {
        _bookService.BorrowBook(bookId);
    }
}

Here We can see we have not create object of BookService so BookController does not need to know about BookService dependencies. In order to get this working we need to use third party dependency injection tools. For .Net project i would recommend winsor container which is more flexible to use. Following tutorial illustrate how to use winsor for dependency injection.

http://stw.castleproject.org/Windsor.MainPage.ashx

No comments:

Post a Comment