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