【问题标题】:Implementing a custom model binder in MVC to resolve types from container在 MVC 中实现自定义模型绑定器以从容器中解析类型
【发布时间】:2012-08-19 12:55:19
【问题描述】:

简而言之,我的问题归结为:

我需要在 MVC4 中实现一个自定义模型绑定器,它可以从容器/服务定位器中解析模型,无论如何。我已经实现了以下模型绑定器:

public class ServiceLocatorModelBinder : DefaultModelBinder
{
    private readonly IServiceLocator _serviceLocator;

    public ServiceLocatorModelBinder(IServiceLocator serviceLocator)
    {
        _serviceLocator = serviceLocator;
    }

    protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
    {
        var typeValue = bindingContext.ValueProvider.GetValue(bindingContext.ModelName + ".ModelType");
        var type = Type.GetType(
            (string)typeValue.ConvertTo(typeof(string)),
            true
        );
        var model = _serviceLocator.GetInstance(modelType);
        bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, type);
        return model;
    }
}

现在我想用它代替 mvc 中的 DefaultModelBinder 来解析我的所有模型。我该怎么做?

为了澄清我完全需要这样做(通常认为最好的做法是为视图模型/模型使用具体的简单类),是我正在尝试使用自动生成代理来代替我的概念整个应用程序中的简单视图模型/poco 类,因此我没有要绑定的具体类型。我希望实现的目标是采用保持模型/视图模型简单的模式,并通过使任何人都无法向这些类添加任何逻辑来进一步执行它。这就是我需要一个容器来解析模型类型的地方。

【问题讨论】:

    标签: c# asp.net-mvc asp.net-mvc-4 model-binding proxy-classes


    【解决方案1】:

    我该怎么做?

    您可以在Application_Start 中将默认模型绑定器替换为自定义模型绑定器:

    IServiceLocator sl = ...
    ModelBinders.Binders.DefaultBinder = new ServiceLocatorModelBinder(sl);
    

    【讨论】:

    • 啊,谢谢,这就是我一直在寻找的东西,我会试一试,如果可行,然后将其标记为答案。感谢您的快速回复:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-04
    • 2015-11-10
    相关资源
    最近更新 更多