views:

130

answers:

3

Normally I would do this:

public class DBFactory
{
        public UserDAO GetUserDao()
        {
               return new UserDao();     
        }

}

Where UserDao being the concrete implementation of IUserDao.

So now my code will be littered with:

DBFactory factory = new DBFactory();

IUserDao userDao = factory.GetUserDao();

User user = userDao.GetById(1);

Now if I wanted to swap implementaitons, I would have to go to my DBFactory and change my code to call a different implementation.

Now if I used NINject, I would bind the specific implementation on application startup, or via a config file. (or bind based on specific parameters etc. etc.).

Is that all there is too it? Or is there more?

(reason I am asking if I want to know how it will help me here: http://stackoverflow.com/questions/1930328/help-designing-a-order-manager-class)

+2  A: 

In a word, yes. Your code would then change in structure, so your dependencies would be passed in via the constructor (or setters, which I am personally not a fan of). You would no longer say "new XXX()" for services in the body of your methods.

You also would not likely need the factory anymore at all, since the DI framework can act as a factory. You would likely just need a constructor dependency on IUserDAO.

So something like:

public class ClassThatNeedsUserDAO
{
     private readonly IUserDAO _userDAO;
     public ClassThatNeedsUserDAO(IUserDAO userDAO)
     {
         _userDAO = userDAO;
     }

     public User MyMethod(userId)
     {
         return _userDAO.GetById(int userId);
     }     
}
Phil Sandler
Bind<IUserDAO>().To<UserDAO>() would make everything work.
LukLed
+1  A: 

There is more to it, one example would be if the constructor of UserDao required some other objects to be passed as arguments (dependencies).

You could have ninject automatically create and inject those objects, saving some lines of code but more importantly ensuring that every class is loosely coupled with its dependencies.

Paul Creasey