asp.net-mvc – MVC 3中ModelBinder构造函数注入的示例IModelBin
发布时间:2020-12-16 04:13:07 所属栏目:asp.Net 来源:网络整理
导读:我需要将自定义的ModelBinder连接到MVC 3中的DI容器,但我无法使其工作. 所以.这就是我所拥有的: 具有构造函数注入服务的ModelBinder. public class ProductModelBinder : IModelBinder{ public ProductModelBinder(IProductService productService){/*sets
我需要将自定义的ModelBinder连接到MVC 3中的DI容器,但我无法使其工作.
所以.这就是我所拥有的: public class ProductModelBinder : IModelBinder{ public ProductModelBinder(IProductService productService){/*sets field*/} // the rest don't matter. It works. } 如果我像这样添加它,我的活页夹工作正常: ModelBinders.Binders.Add(typeof(Product),new ProductModelBinder(IoC.Resolve<IProductService>())); 但这是做旧的方式,我不希望如此. 我需要的是如何将模型绑定器挂钩到我已注册的IDependencyResolver. 根据Brad Wilson的说法,秘密是使用IModelBinderProvider实现,但是对于如何连接它非常不清楚. (in this post) 有人有例子吗? 解决方法
在编写我的MVC 3应用程序时遇到了同样的情况.我最终得到了这样的东西:
public class ModelBinderProvider : IModelBinderProvider { private static Type IfSubClassOrSame(Type subClass,Type baseClass,Type binder) { if (subClass == baseClass || subClass.IsSubclassOf(baseClass)) return binder; else return null; } public IModelBinder GetBinder(Type modelType) { var binderType = IfSubClassOrSame(modelType,typeof(xCommand),typeof(xCommandBinder)) ?? IfSubClassOrSame(modelType,typeof(yCommand),typeof(yCommandBinder)) ?? null; return binderType != null ? (IModelBinder) IoC.Resolve(binderType) : null; } } 然后我在我的IoC容器中注册了这个(在我的情况下是Unity): _container.RegisterType<IModelBinderProvider,ModelBinderProvider>("ModelBinderProvider",singleton()); 这对我有用. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- ASP.NET LoginUser.DestinationPageUrl无法正常工作
- asp.net-mvc-4 – 在MVC中的App_Start()文件夹中使用AuthCo
- [译]ASP.NET Core 2.0 路由引擎详解
- .NET Core技术研究-主机Host ASP.NET Core技术研
- asp.net – ASP按钮(命令与提交)
- asp.net-mvc – asp.net mvc排除来自搜索引擎抓取的动作
- asp.net – 什么设置的User.Identity.Name和User.Identity.
- asp.net – 有没有办法动态包装/拦截HtmlHelper扩展方法.想
- 关闭一个子目录的ASP.Net WebForms身份验证
- asp.net – 在iframe中显示PDF
推荐文章
站长推荐
- asp-classic – ASP经典CDO电子邮件消息在textbo
- asp.net – 对于单个页面,requestFiltering allo
- asp.net-core – ASP.NET核心DisplayAttribute本
- asp.net – 为什么设置AssociatedUpdatePanelId时
- asp.net-mvc-3 – MVC3 EditorFor动态属性(或需要
- asp-classic – 请求与Request.QueryString
- ASP.NET MVC3 JQuery Validate Plugin自定义错误
- ASP.Net WCF服务的Thread.CurrentPrincipal被联邦
- asp.net-mvc – 实体创建抛出“没有为此对象定义
- asp.net – 为什么Global.asax事件在我的ASP.NET
热点阅读