[英].NET MVC Dependency Injection with Ninject
我剛開始用.NET編程,我在實現dependency injection (using Ninject)
方面遇到了一些問題dependency injection (using Ninject)
。
我正在創建某種餐飲應用程序,用戶可以瀏覽城鎮,城鎮瀏覽餐館和餐館瀏覽食物。
我正在使用UnitOfWork和存儲庫模式,例如我通過id訪問城鎮,如下所示:
_unitOfWork.TownRepository.GetByID(id);
現在我開始在應用程序中實現服務,我遇到了dependency injection
。
我創建了ITownService
, IRestaurantService
和IFoodService
(因為我在UnitOfWork
有TownRepository
, RestaurantRepository
和FoodRepository
)。
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 IEnumerable<Town> GetAll()
{
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
,但它們應該是類似的,當然有些附加方法可以解決這個問題。 例如在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
而不是我在TownService
, RestaurantService
和FoodService
中TownService
ITownService
, IRestaurantService
和IFoodService
,還是可以這樣嗎?
綁定時我需要綁定什么?
kernel.Bind<IUnitOfWork>().To<UnitOfWork>();
kernel.Bind<ITownService>().To<TownService>();
kernel.Bind<IRestaurantService>().To<RestaurantService>();
kernel.Bind<IFoodService>().To<TownService>();
像這樣的東西?
簡而言之 - 我需要為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>();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.