Proper Dependency Injection In MVC
Controller code
public class ThreadController : Controller
{
private ThreadViewModelBuilder _builder = null;
public ThreadController(ThreadViewModelBuilder builder)
{
_builder = builder;
}
//
// GET: /Threads/Thread/
public ActionResult Index()
{
List<Thread> model = _builder.GetAllThreads();
return View(model);
}
}
ViewModelBuilder code
public class ThreadViewModelBuilder
{
protected readonly IThreadBusiness iThreadBusiness;
public ThreadViewModelBuilder(IThreadBusiness iThreadBusiness)
{
this.iThreadBusiness = iThreadBusiness;
}
public List<Thread> GetAllThreads()
{
List<Thread> threads = iThreadBusiness.GetThreads();
return threads;
}
}
Business implementation code
public class ThreadBusiness : IThreadBusiness
{
IThreadRepository iThreadRepository = null;
public ThreadBusiness(IThreadRepository iThreadRepository)
{
this.iThreadRepository = iThreadRepository;
}
public List<Thread> GetThreads()
{
return iThreadRepository.GetThreads().ToList();
}
}
Repository implementation code
public class ThreadRepository : IThreadRepository
{
private IssuesEntities context;
public ThreadRepository()
{
this.context = new IssuesEntities();
}
public IQueryable<Thread> GetThreads()
{
return (from threads in context.Thread
select threads);
}
}