我刚开始学习在.NET上编程,实现依赖注入(使用Ninject)时遇到了一些问题。
我正在创建一种餐饮应用程序,用户可以浏览城镇,在城镇中浏览餐馆,在餐馆中浏览食物。
我正在使用UnitOfWork和Repository模式,例如,我这样按id访问town:
_unitOfWork.TownRepository.GetByID(id);
现在我开始将服务实现到应用程序中,我遇到了需要进行依赖注入
的情况。
我已经创建了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
而不是ITownService
,IRestaurantService
和IFoodService
吗? 在TownService
,RestaurantService
和FoodService
中我应该继承哪个服务接口呢?或者像这样也可以吗?
绑定时我需要绑定什么?
kernel.Bind<IUnitOfWork>().To<UnitOfWork>();
kernel.Bind<ITownService>().To<TownService>();
kernel.Bind<IRestaurantService>().To<RestaurantService>();
kernel.Bind<IFoodService>().To<TownService>();
需要这样做吗?
简而言之 - 我需要用 Ninject
添加依赖注入,我遇到了一些问题,需要帮助。
非常感谢您提前的帮助。
ITownService
,那么IRestaurantService
和IFoodService
呢?你是如何创建这些变量的? - Nitin Sawant