asp.net-mvc - MVC 3 中 ModelBinder 构造函数注入(inject)的 IModelBinderProvider 实现示例

标签 asp.net-mvc asp.net-mvc-3 modelbinders

我需要将我的自定义 ModelBinder 连接到 MVC 3 中的 DI 容器,但我无法让它工作。

所以。这就是我所拥有的: 带有构造函数注入(inject)服务的 ModelBinder。

public class ProductModelBinder : IModelBinder{
  public ProductModelBinder(IProductService productService){/*sets field*/}
  // the rest don't matter. It works.
}

如果我像这样添加它,我的 Binder 工作正常:

ModelBinders.Binders.Add(typeof(Product),
     new ProductModelBinder(IoC.Resolve<IProductService>()));

但这是旧的做法,我不希望那样。

我需要的是有关如何将该 modelbinder 连接到我注册的 IDependencyResolver 的帮助。

根据 Brad Wilson 的说法, secret 是使用 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-mvc - MVC 3 中 ModelBinder 构造函数注入(inject)的 IModelBinderProvider 实现示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4392048/

相关文章:

asp.net - asp.net 5 与 asp.net mvc 不同吗?

asp.net - AJAX.BeginForm 发送空 FormCollection 列表到 MVC Controller

asp.net-mvc - ASP NET MVC 中的模型绑定(bind)数据库实体

asp.net-mvc - ASP.Net MVC ModelBindingContext 类——它的模型值是如何填充的?

ASP.Net MVC优雅的UI和ModelBinder授权

c# - 尝试编辑不存在的项目的最佳实践?

asp.net-mvc - 具有 PerWebRequest LifeStyle 依赖项的单元测试 Controller

asp.net-mvc - 设置配置文件以在 asp net mvc 4 中存储参数的最佳方法

asp.net-mvc-3 - 如何在 MVC Razor View 中使用具有多个输入的内联模板

c# - 将 PagedList 与 View 模型 MVC 3 一起使用