【问题标题】:Example IModelBinderProvider implementation for ModelBinder constructor injection in MVC 3MVC 3 中 ModelBinder 构造函数注入的示例 IModelBinderProvider 实现
【发布时间】:2010-12-09 15:21:07
【问题描述】:

我需要将我的自定义 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)

有人有例子吗?

【问题讨论】:

  • IModelBinderProvider 将是您自己的实现。碰巧我写了一篇关于这件事的博客文章buildstarted.com/2010/12/02/…希望这有帮助
  • 是的,效果很好。我只是将 CreateInstance() 东西替换为 var instance = (IModelBinder) DependencyResolver.Current.GetService(type);谢谢! .
  • 我仍然认为应该可以使用泛型进行更干净的实现。我想我需要睡在那上面;)

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


【解决方案1】:

我在编写 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());

这对我有用。

【讨论】:

    【解决方案2】:

    您需要编写自己的IModelBinderProvider 并将其注册到ModelBinderProviders.BinderProviders 集合中:

    public class YourModelBinderProvider : IModelBinderProvider {
        public IModelBinder GetBinder(Type modelType) {
             if(modelType == typeof(Product)) {
                 return new ProductModelBinder(...);
             }
             return null;
        }
    }
    

    在 Global.asax 中:

    ModelBinderProviders.BinderProviders.Add(new YourModelBinderProvider());
    

    【讨论】:

    • 最好在 IoC 中注册 IModelBinderProvider 以便 MVC 自动请求它还是使用 BinderProviders.Add(...) 显式注册它?此外,如果我们尝试处理多个活页夹(基于模型类型),是否有您推荐的模式?
    • 无论哪种方式都可以。我想我只是更喜欢传统的方法。
    • 您如何尝试处理多个活页夹?返回非空活页夹的第一个活页夹提供者获胜。所以这只是适当地订购东西的问题。
    • 看看我下面的答案...我目前正在使用这是一个开发项目。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多