asp.net-mvc-3 - 用作 Action 方法参数的 View Model 实例的构造函数注入(inject)

标签 asp.net-mvc-3 dependency-injection viewmodel constructor-injection

创建 View 模型时,您可以将选项(例如,在下拉列表中使用)填充到 View 模型的 setter 属性中。
问题是,当该 View 模型稍后作为参数(由框架!)传递给操作方法时,这些属性值并没有自动变为
重新填充,因此如果由于验证错误需要重新显示表单,则需要再次重新填充这些选项。

我在这个问题中特别要求的一个潜在解决方案是如何使 MVC 框架通过构造函数注入(inject)实例化 View 模型,这将为 View 模型构造函数提供某种数据访问对象的实现(例如存储库) 可用于在 View 请求选项时检索选项(例如,在辅助方法“DropDownListFor”中)?

我认为该解决方案可能与 IModelBinderProvider 或 IModelBinder 的实现有关,但是在从网上的示例代码片段中试验了这些东西之后,我仍在寻找一个完整的工作示例,具有可下载的可执行代码而没有任何遗漏一 block 如何把所有的东西放在一起。

如果您正在寻找有关如何填充选择列表的替代讨论,例如使用“Dependecy Lookup”而不是“Dependecy Injection”,您可能需要查看以下讨论:
在 GET/POST 上为 ViewModel 填充 SelectList 的最佳方式
Best way to populate SelectList for ViewModel on GET/POST

几天前,我在那个线程中写了以下关于我现在在这个线程中寻找的“依赖注入(inject)”的后续问题:
https://stackoverflow.com/a/8674525/310457
(它提供了一个关于我正在寻找解决方案的问题的代码示例)

但是,我没有希望有人会找到标题不太具体的旧线程,而是创建了这个新问题,其中包含一个关于我正在寻找的更具体的主题。
我还将为任何想要跟进我正在寻找的特定解决方案的人提供从该线程到这个新问题的链接。

最佳答案

我假设你想让你的 ViewModels 通过它们的构造函数自动注入(inject)一些东西——例如某种配置对象, View 将用来确定要显示的内容。我还假设当 MVC 尝试从 Controller 操作的参数自动创建和绑定(bind)模型实例时,这种方法会导致“没有为此对象定义无参数构造函数”错误。然后假设我们将使用 DI 框架在运行时自动将 SiteConfig 对象注入(inject)到我们的 Controller 中。

这意味着我们唯一需要解决的问题是,当它们被自动绑定(bind)时,如何将注入(inject)的对象从我们的 Controller 中获取到其 Actions 的 ViewModel 中。

所以让我们定义一个基础模型供其他人继承。

BaseViewModel

public class BaseViewModel
{
    public ISiteConfig SiteConfig { get; set; }

    public BaseViewModel(ISiteConfig siteConfig)
    {
        this.SiteConfig = siteConfig;
    }
}

现在让我们创建一个继承自它的模型。

IndexViewModel
public class IndexViewModel : BaseViewModel
{
    public string SomeIndexProperty { get; set; }

    public IndexViewModel (ISiteConfig siteConfig) : base(siteConfig) {}
}

现在让我们定义一个基础 Controller ,我们的 Controller 将从中继承。

基本 Controller
public abstract class BaseController : Controller
{
    protected BaseController(ISiteConfig siteConfig)
    {
        _siteConfig = siteConfig;
    }

    private readonly ISiteConfig _siteConfig;

    public ISiteConfig SiteConfig
    {
        get
        {
            return _siteConfig;
        }
    }
}

现在我们定义我们的实际 Controller 。

首页 Controller
public HomeController: BaseController
{
    public HomeController(ISiteConfig siteConfig): base(siteConfig) {}
}

假设我们使用 Ninject 进行 DI,Ninject 将被配置为自动创建 Controller 并传递一个具体的 ISiteConfig在运行时将对象放入其构造函数中。

现在我们将我们的 Action 添加到 Controller 中。

指数行动
public ActionResult Index(IndexViewModel model)
{
    return View(model);
}

因此,如果您尝试调用索引操作,MVC 将在不执行任何其他操作的情况下爆炸并出现“无参数构造函数”错误,因为 MVC 找不到不带参数的 ViewModel 构造函数。

所以,答案。我们需要覆盖默认的 ModelBinder。

BaseViewModelBinder
public class BaseViewModelBinder : DefaultModelBinder
{
    protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
    {
        if (modelType == typeof(BaseViewModel) || modelType.IsSubclassOf(typeof(BaseViewModel)))
        {
            var baseControl = controllerContext.Controller as BaseController;
            if (baseControl == null)
            {
                throw new Exception("The Controller must derive from BaseController");
            }

            var instance = Activator.CreateInstance(modelType, baseControl.SiteConfig);
            bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => instance, modelType);
            return instance;
        }
        else
        {
            return base.CreateModel(controllerContext, bindingContext, modelType);
        }
    }
}

我们需要将其设置为 global.asax.cs 中的默认模型绑定(bind)器:
protected void Application_Start()
{
    ...
    ModelBinders.Binders.DefaultBinder = new BaseViewModelBinder();
}

就这样。如您所见,当您现在查看 Index Action 时,MVC 将使用我们自定义的模型绑定(bind)器。它将意识到 IndexViewModel 派生自 BaseViewModel,因此将尝试使用它可以在 Action 的 Controller 中找到的 ISiteConfig 启动 IndexViewModel 实例(因为 Controller 派生自 BaseController)。

关于asp.net-mvc-3 - 用作 Action 方法参数的 View Model 实例的构造函数注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8693141/

相关文章:

jquery 表单发布了两次

java - Guice 通用提供程序(提供程序本身是通用的,而不是它绑定(bind)到的类)

android - 当 "do not keep activity"开发选项打开时,ViewModel 被清除

c# - 绑定(bind)对象永远不会为空

javascript - 放下图像后如何在 Canvas 中显示图像的宽度,高度和 Angular 值

c# - 无障碍客户端验证错误

silverlight - 如何使用 Silverlight 和 MVVM 设计复合 View 和 View 模型?

c# - Ninject 的 .NET MVC3 服务定位器/依赖解析器问题

c# - 使用 Simple Injector 和 IHttpControllerActivator 解决 ASP.NET Web API 中的依赖关系

asp.net-mvc - 如何正确使用 View 模型