我需要在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>()));

但这是这样做的旧方式,我不想那样。

我需要的是如何将该模型框架挂接到我注册的IdependencencyResolver上。

根据布拉德·威尔逊(Brad Wilson)的说法,该秘密正在使用Imodelbinder -Provider实现,但对于如何将其连接起来非常清楚。 ((在这篇文章中)

有人有榜样吗?

有帮助吗?

解决方案

编码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容器中注册了此内容(在我的情况下):

_container.RegisterType<IModelBinderProvider, ModelBinderProvider>("ModelBinderProvider", singleton());

这对我有用。

其他提示

你需要写自己的 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());
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top