Žel*_*ber 11 c# asp.net asp.net-mvc dependency-injection ninject
我刚开始用.NET编程,我在实现时遇到了一些问题dependency injection (using Ninject).
我正在创建某种餐饮应用程序,用户可以浏览城镇,城镇浏览餐馆和餐馆浏览食物.
我正在使用UnitOfWork和存储库模式,例如我通过id访问城镇,如下所示:
_unitOfWork.TownRepository.GetByID(id);
Run Code Online (Sandbox Code Playgroud)
现在我开始在应用程序中实现服务,我遇到了需要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 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;
}
}
Run Code Online (Sandbox Code Playgroud)
我还没有实现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;
}
}
Run Code Online (Sandbox Code Playgroud)
类似的将是RestaurantController和FoodController当然只是构造注射.
我如何Ninject在这样的例子中使用?我需要一些全局IService,而不是ITownService,IRestaurantService而且IFoodService我会在inherid TownService,RestaurantService而且FoodService还是好喜欢这个?
绑定时我需要绑定什么?
kernel.Bind<IUnitOfWork>().To<UnitOfWork>();
kernel.Bind<ITownService>().To<TownService>();
kernel.Bind<IRestaurantService>().To<RestaurantService>();
kernel.Bind<IFoodService>().To<TownService>();
Run Code Online (Sandbox Code Playgroud)
像这样的东西?
简而言之 - 我需要添加依赖注入Ninject吗?
我真的遇到了这个问题,需要帮助.
非常感谢前进.
hut*_*oid 17
从包管理器控制台运行此命令:
Install-package Ninject.MVC3
Run Code Online (Sandbox Code Playgroud)
这将添加一个类 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>();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8659 次 |
| 最近记录: |