【发布时间】:2016-02-01 18:35:55
【问题描述】:
我有 ProductController.cs
namespace AmazonProductAdvertisingAPI.WebUI.Controllers
{
public class ProductController : Controller
{
public ProductController(IProductCollection productCollection)
{
_productCollection = productCollection;
}
public static string Title
{
get
{
return _title;
}
set
{
_title = value;
}
}
public static int PageNumber
{
get
{
return _pageNumber;
}
set
{
_pageNumber = value;
}
}
public static int ItemsPerPage
{
get
{
return _itemsPerPage;
}
set
{
_itemsPerPage = value;
}
}
// GET: Product
public ActionResult List(int page = 1, string search = null)
{
ProductListViewModel model = new ProductListViewModel
{
Products = _productCollection.Products
.OrderBy(product => product.Title)
.Skip((page - 1) * pageSize)
.Take(pageSize),
PagingInfo = new PagingInfo
{
CurrentPage = page,
ItemsPerPage = pageSize,
TotalItems = _productCollection.Products.Count()
}
};
return View(model);
}
}
}
NinjectDependencyResolver.cs
namespace AmazonProductAdvertisingAPI.WebUI.Infrastructure
{
public class NinjectDependencyResolver : IDependencyResolver
{
private IKernel kernel;
public NinjectDependencyResolver(IKernel kernelParam)
{
kernel = kernelParam;
AddBindings();
}
public object GetService(Type serviceType)
{
return kernel.TryGet(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType)
{
return kernel.GetAll(serviceType);
}
private void AddBindings()
{
// Create dependency here
kernel.Bind<IProductCollection>().To<AmazonProductCollection>()
.WhenInjectedInto<ProductController>()
.WithConstructorArgument("title", ProductController.Title)
.WithConstructorArgument("pageNumber", ProductController.PageNumber)
.WithConstructorArgument("itemsPerPage", ProductController.ItemsPerPage);
}
}
}
AmazonProductCollection 类有构造函数:
public AmazonProductCollection(string title, int pageNumber, int itemsPerPage)
我希望 AmazonProductCollection 从产品控制器的操作列表参数中获取自己的参数,因为当用户填写 TextBoxt 并单击 html-view 表单中的“搜索”按钮时,它会获取其中的一些参数。例如,我想使用操作列表中的参数字符串“search”并作为构造函数参数“title”传输到 AmazonProductCollection。
我读了这篇文章:How to pass parameters to a transient object created by Ninject?,但我不明白如何在我的情况下创建相同的东西。
有人可以帮我处理 Ninject 吗?
【问题讨论】:
标签: c# asp.net-mvc dependency-injection ninject ninject.web.mvc