【发布时间】: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