【问题标题】:ASP.NET WebApi Model Binding with Dependency Injection使用依赖注入的 ASP.NET WebApi 模型绑定
【发布时间】:2017-01-31 12:18:22
【问题描述】:

我有一个用 ASP.NET MVC 5 编写的 Web 应用程序,它具有完美运行的 Razor 视图。我有一组模型类,它们需要在构造函数中使用 ISomething,并且使用 Unity 将 ISomething 注入其中。一切都很好。

我有这样的模型类:

public class SecurityRoleModel : PlainBaseModel
{
    #region Constructor
    /// <summary>
    /// Initializes a new instance of the <see cref="SecurityRoleModel"/> class.
    /// </summary>
    /// <param name="encryptionLambdas">The encryption lambdas.</param>
    public SecurityRoleModel(IEncryptionLambdas encryptionLambdas)
    {
    }
    #endregion
}

为了让注入正常工作,我必须实现一个自定义的DefaultModelBinder,它负责像这样处理模型构造函数注入:

public class InjectableModelBinder : DefaultModelBinder
{
    protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
    {
        if (modelType == typeof(PlainBaseModel) || modelType.IsSubclassOf(typeof(PlainBaseModel)))
            return DependencyResolver.Current.GetService(modelType);

        return base.CreateModel(controllerContext, bindingContext, modelType);
    }
}

再次,这是针对应用程序的 MVC 部分,但现在是丑陋的部分:我必须实现一组服务 (WebAPI) 来处理这些模型,并且我认为我可以做一些类似于 MVC 的事情DefaultModelBinder 在 WebAPI 中,但似乎并不像我想象的那么容易。

现在我的问题来了——虽然我已经阅读(我认为)很多关于自定义IModelBinder(WebAPI)实现的帖子,但我不能说我找到了我正在寻找的东西;我想要的是找到一种不重新发明轮子的方法(读作“从头开始写一个IModelBinder”),我只想有一个实例化模型类的地方并有可能放置我的代码从 DI 中获取模型类的实例。

我希望我已经足够清楚了。提前谢谢你。

埃夫丁

【问题讨论】:

  • 使用TypeConvertor 怎么样?您应该能够从 convert factory 方法访问依赖解析器以新建模型。
  • 感谢您的回复。您是要覆盖 ConvertFrom 或 ConvertTo 吗?我尝试过使用 ConvertFrom,但我只收到字符串,我真的不想重新创建转换。

标签: c# asp.net-mvc asp.net-web-api asp.net-mvc-5 unity-container


【解决方案1】:

虽然没有 MVC DefaultModelBinder 广泛,而且它仅涵盖序列化器/反序列化器为 JSON.NET 的情况,但我为我的问题找到的解决方案如下:

a) 像这样从Newtonsoft.Json.Converters 实现CustomCreationConverter&lt;T&gt; 的自定义版本:

public class JsonPlainBaseModelCustomConverter<T> : CustomCreationConverter<T>
{
    public override T Create(Type objectType)
    {
        return (T)DependencyResolver.Current.GetService(objectType);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.Null)
            return null;

        return base.ReadJson(reader, objectType, existingValue, serializer);
    }
}

b) 在WebApiConfig 类中注册自定义转换器,Register 方法如下:

config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new JsonPlainBaseModelCustomConverter<PlainBaseModel>());

虽然这可能不是最佳情况,但它完美地解决了我的问题。

如果有人知道更好的解决方案,请告诉我。

谢谢!

【讨论】:

    猜你喜欢
    • 2012-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-02
    • 1970-01-01
    相关资源
    最近更新 更多