首先介紹一些背景知識。如何向模型中注入請求特定的詳細信息
我想提供一個模型API來我的同事,看起來有點像這樣。
public class ProductFilterViewModel : ModelBase
{
[SelectItem ManagerType = typeof(UnitManager)
SelectMethod = "GetUnits"
TextProperty = "Name"
ValueProperty = "Text"]
IEnumerable<SelectListItem> UnitSelectItems { get; set; }
public IModelContext ModelContext { get; set; }
// More properties etc.
}
public interface IModelContext
{
string AccessToken { get; }
}
我的API的用戶應該或者能夠創建新的實例(通過工廠方法,或使用NInject容器,無論是細)或有這樣的結合的實例的控制器參數,並具有以下發生 - 應該填充由[SelectItem]引起的屬性,並且應該注入IModelContext的實例。現在
public class SomeController : Controller
{
public ActionResult Index()
{
// or whatever
ProductFilterViewModel model = this.Container.Get<ProductFilterViewModel>();
return View(model);
}
[HttpPost]
public ActionResult Index(ProductFilterViewModel model)
{
model.RunSearch(); // will internally use model.ModelContext.AccessToken;
return View(model);
}
}
,該的accessToken財產來自一個cookie並是模型內發生的任何數據庫訪問必要的 - 包括[的SelectItem]
我能得到這個工作,由於這些屬性的自動填充與模型完美綁定。我在哪裏掙扎的是如何在不需要重複代碼的情況下,在非綁定的情況下進行此操作。理想情況下,模型活頁夾將使用相同的工廠/容器。我已經嘗試通過DependencyResolver.Current設置東西,但隨後我在如何配置容器以便在請求時從Cookie注入AccessToken。唯一的其他想法我是配置在ControllerBase類的容器中,然後在我的模型綁定從ControllerContext訪問它,但似乎噁心。