0

我有一个Web应用程序,写在ASP.NET MVC 5与Razor视图,完美的作品。我有一组模型类,在构造函数中需要ISomething,而ISomething是使用Unity注入的。一切都很好。ASP.NET WebApi模型绑定与依赖注入

我有这样的模型类:

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在WebA中PI,但似乎并不像我想象的那么容易。 (我认为)很多关于自定义IModelBinder(WebAPI)的实现的帖子,我不能说我找到了我在找的东西;我想要的是找到一种不重新发明轮子的方法(被认为是“从头开始编写IModelBinder),我只想有一个模型类实例化的地方,并有可能将我的代码从DI得到的模型类的实例。

我希望我足够清楚了。谢谢你在前进。

Evdin

+0

如何使用[TypeConvertor](http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api)?您应该能够从convert factory方法访问依赖关系解析器,以创建新的模型。 –

+0

感谢您的回复。你的意思是覆盖ConvertFrom或ConvertTo?我试过ConvertFrom,但我只收到字符串,我真的不想重新创建转换。 – Edi

回答

0

虽然并不像MVC DefaultModelBinder为广泛,它仅覆盖当串行器/解串器是JSON.NET的情况下,我发现我的问题的解决方案如下:

一)从Newtonsoft.Json.Converters实施CustomCreationConverter<T>定制版本是这样的:

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); 
    } 
} 

二)在WebApiConfig类,Register方法这样注册自定义转换器:

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

虽然它可能不是最佳情况,它完全涵盖了我的问题。

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

谢谢!