Currently, I'm building a website with 2 layers.
- Web UI: this is a MVC 4 project, used to interact with users
- Data Access: this is a C# library. This layer is responsible for interacting with database.
I'm using Ninject for Dependency Injection. Up to now, it's OK. But now, I want to insert a new layer between Web UI and Data Access, called Business Logic. So the architecture would be:
- Web UI: uses interface from business logic.
- Business logic: uses interface from data access.
- Data access: stays the same.
My question is, how should I configure my Ninject in Web UI and Business Logic to achieve what I want? Here is my source code at this time:
Data Access Layer:
Interface IHotelRepository.cs
public interface IHotelRepository
{
IQueryable<Hotel> Hotels { get; }
}
Concrete class HotelRepository.cs
public class HotelRepository : IHotelRepository
{
private HotelDbEntities context = new HotelDbEntities();
public IQueryable<Hotel> Hotels { get { return context.Hotels; } }
}
Web UI layer:
NinjectControllerFactory.cs
public class NinjectControllerFactory : DefaultControllerFactory
{
private IKernel ninjectKernel;
public NinjectControllerFactory()
{
ninjectKernel = new StandardKernel();
AddBindings();
}
protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
{
return controllerType == null ? null : (IController) ninjectKernel.Get(controllerType);
}
private void AddBindings()
{
ninjectKernel.Bind<IHotelRepository>().To<HotelRepository>();
}
}
Global.asax.cs
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());
}
}
HotelController.cs
public class HotelController : Controller
{
private IHotelRepository hotelRepository;
public HotelController(IHotelRepository repository)
{
hotelRepository = repository;
}
public ActionResult List()
{
return View(hotelRepository.Hotels);
}
}
Thanks for your help.