加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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容器,但我无法使其工作.

所以.这就是我所拥有的:
具有构造函数注入服务的ModelBinder.

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());

这对我有用.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读