如果您尝试将事物注入控制器以删除所有方法中的“var thing = thingFactory.Get(id)”行,则可以使用 ASP.NET MVC 自定义模型绑定器在开始之前执行检索你的方法代码。
如果您的路线看起来像: /{controller}/{action}/{id} ,那么您将让 id 查找您的值。
模型绑定将允许您的方法签名如下所示:
public ActionResult SomeDetails(int id, Thing thing)
{
模型绑定和验证在方法代码执行之前触发。DefaultModelBinder 只会从 FormCollection 或其他非持久源填充您的类。
我推荐的技巧是为执行查找的 Thing 类提供自定义模型绑定器 (IModelBinder)。从 DefaultModelBinder 派生,注入您的 IThingFactory,并覆盖 BindModel() 以按照您的方式进行查找。
public class ThingModelBinder : DefaultModelBinder
{
IThingFactory ThingFactory;
public ThingModelBinder(IThingFactory thingFactory)
{
this.IThingFactory = thingFactory;
}
protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
{
Thing thing = new Thing();
string id_string = controllerContext.RouteData.Values["id"].ToString();
int id = 0;
Int32.TryParse(id_string, out id);
var thing = thingFactory.Get(id);
return thing;
}
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
if (bindingContext == null)
{
throw new ArgumentNullException("bindingContext");
}
// custom section
object model = this.CreateModel(controllerContext, bindingContext, typeof(Thing));
// set back to ModelBindingContext
bindingContext.ModelMetadata.Model = model;
// call base class version
// this will use the overridden version of CreateModel() which calls the Repository
// object model = BindComplexModel(controllerContext, bindingContext);
return base.BindModel(controllerContext, bindingContext);
}
然后,您将在 global.asax Application_Start() 中配置模型绑定器,您已经在其中创建了容器:
// Custom Model Binders
System.Web.Mvc.ModelBinders.Binders.Add(
typeof(MyCompany.Thing)
, new MyMvcApplication.ModelBinders.ThingModelBinder(
WindsorContainer.Resolve<IThingFactory>()
)
);
这将导致您的自定义模型绑定器被调用。
您以正常方式解决 Windsor 依赖项。
这是基于我做的一个帖子。