I hit a little road block trying to set up DI.
So given that I have this controller:
public UsersController(IUnitOfWork unitOfWork)
{
// Stuff
}
I previously had this UnitOfWork implementation that accessed my repositories directly.
public class UnitOfWork : IUnitOfWork, IDisposable
{
private readonly DbContext _context = new DbContext();
public IRepository<User> Users { get { return new UserRepository(_context); } }
}
Ninject UnitOfWork code: Bind<IUnitOfWork>().To<UnitOfWork>().InRequestScope();
Now this actually works fine. However I want to change it so that instead of UnitOfWork containing the repositories, it contains services which take in multiple repositories.
public class UserService : IUserService
{
private readonly IUserRepository _userRepository;
public UserService(IUserRepository userRepository, /* Other repositories */)
{
_userRepository = userRepository;
}
}
Right now the only solution I can come up with is
public class UnitOfWork : IUnitOfWork, IDisposable
{
private readonly DbContext _context = new DbContext();
public IUserService UserService
{
get
{
return new UserService(new UserRepository(_context), /* etc. */);
}
}
}
This doesn't seem right. Now I'm creating all of the service dependencies myself.
I've seen posts on StackOverflow mentioning that it's better to have services access the multiple repositories and handle the business logic rather than having the controller (MVC application) worry about it.
Can't find any specifics on how to actually do this properly though. So how could I use Ninject to do what I'm after?