Unity IoC and MVC modelbinding
- by danielovich
Is it ok to have a static field in my controller for my modelbinder to call ?
Eg.
public class AuctionItemsController : Controller
{
private IRepository<IAuctionItem> GenericAuctionItemRepository;
private IAuctionItemRepository AuctionItemRepository;
public AuctionItemsController(IRepository<IAuctionItem> genericAuctionItemRepository, IAuctionItemRepository auctionItemRepository) {
GenericAuctionItemRepository = genericAuctionItemRepository;
AuctionItemRepository = auctionItemRepository;
StaticGenericAuctionItemRepository = genericAuctionItemRepository;
}
internal static IRepository<IAuctionItem> StaticGenericAuctionItemRepository;
here is the modelbinder
public class AuctionItemModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {
if (AuctionItemsController.StaticGenericAuctionItemRepository != null) {
AuctionLogger.LogException(new Exception("controller is null"));
}
NameValueCollection form = controllerContext.HttpContext.Request.Form;
var item = AuctionItemsController.StaticGenericAuctionItemRepository.GetSingle(Convert.ToInt32(controllerContext.RouteData.Values["id"]));
item.Description = form["title"];
item.Price = int.Parse(form["price"]);
item.Title = form["title"];
item.CreatedDate = DateTime.Now;
item.AuctionId = 1;
//TODO: Stop hardcoding this
item.UserId = 1;
return item;
}}
i am using Unity as IoC and I find it weird to register my modelbinder in the IoC container.
Any other good design considerations I shold do ?