1
我想爲我們的自定義ModelBinders實現依賴注入。現在我有我可以使用DefaultBinder執行依賴注入嗎?
protected void Application_Start()
{
// removed IoC configuration code
ModelBinders.Binders.DefaultBinder = new CastleWindsorModelBinder(this.container, ModelBinders.Binders.DefaultBinder);
// removed configuration code
}
public class CastleWindsorModelBinder : IModelBinder
{
private readonly IWindsorContainer container;
private readonly IModelBinder fallback;
public CastleWindsorModelBinder(IWindsorContainer container, IModelBinder fallback)
{
this.container = container;
this.fallback = fallback;
}
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
try
{
var binder = (IModelBinder)this.container.Resolve(
bindingContext.ModelType.FullName, typeof (IModelBinder));
return binder.BindModel(controllerContext, bindingContext);
}
catch (ComponentNotFoundException)
{
return fallback.BindModel(controllerContext, bindingContext);
}
}
}
但我不確定這是否會導致整體表現不佳。任何人都可以用這種方法分享他自己的經驗嗎?