我刚开始用.NET编程,我在实现时遇到了一些问题dependency injection (using Ninject)
.
我正在创建某种餐饮应用程序,用户可以浏览城镇,城镇浏览餐馆和餐馆浏览食物.
我正在使用UnitOfWork和存储库模式,例如我通过id访问城镇,如下所示:
_unitOfWork.TownRepository.GetByID(id);
现在我开始在应用程序中实现服务,我遇到了需要dependency injection
.
我已经创建ITownService
,IRestaurantService
和IFoodService
(因为我已经TownRepository
,RestaurantRepository
并且FoodRepository
在我的UnitOfWork
).
TownService的样本外观:
public class TownService : ITownService { // initialize UnitOfWork private IUnitOfWork _unitOfWork; public TownService() : this(new UnitOfWork()) { } public TownService(IUnitOfWork unitOfWork) { _unitOfWork = unitOfWork; } public Town GetByID(object id) { return _unitOfWork.TownRepository.GetByID(id); } public IEnumerableGetAll() { return _unitOfWork.TownRepository.Get(); } public bool Insert(Town town) { // validation logic if (!ValidateTown(town)) return false; try { _unitOfWork.TownRepository.Insert(town); _unitOfWork.Save(); } catch { return false; } return true; } public bool Delete(object id) { try { _unitOfWork.TownRepository.Delete(id); _unitOfWork.Save(); } catch { return false; } return true; } public bool Update(Town townToUpdate) { // validation logic if (!ValidateTown(townToUpdate)) return false; try { _unitOfWork.TownRepository.Update(townToUpdate); _unitOfWork.Save(); } catch { return false; } return true; } }
我还没有实现FoodService
与RestaurantService
还,但他们应该是与当前一些additinal方法怎样exepct这一点,我也有类似的.例如,RestaurantService
我可能有public Restaurant GetRestaurantsInTown(Town town){}
或类似的东西.
我希望你有一点应用的感觉.现在回过头来Ninject
.
在我,TownController
我会有这样的事情:
public class TownController : Controller { private ITownService _townService; public TownController(ITownService townService) { _townService = townService; } }
类似的将是RestaurantController
和FoodController
当然只是构造注射.
我如何Ninject
在这样的例子中使用?我需要一些全局IService
,而不是ITownService
,IRestaurantService
而且IFoodService
我会在inherid TownService
,RestaurantService
而且FoodService
还是好喜欢这个?
绑定时我需要绑定什么?
kernel.Bind().To (); kernel.Bind ().To (); kernel.Bind ().To (); kernel.Bind ().To ();
像这样的东西?
简而言之 - 我需要添加依赖注入Ninject
吗?
我真的遇到了这个问题,需要帮助.
非常感谢前进.
从包管理器控制台运行此命令:
Install-package Ninject.MVC3
这将添加一个类 App_Start/NinjectWebCommon.cs
如果你看到底部附近有一个RegisterServices方法.
你只需在那里添加你问题的代码,即
private static void RegisterServices(IKernel kernel) { kernel.Bind<IUnitOfWork>().To<UnitOfWork>(); kernel.Bind<ITownService>().To<TownService>(); kernel.Bind<IRestaurantService>().To<RestaurantService>(); kernel.Bind<IFoodService>().To<TownService>(); }