asp.net-mvc - 带有 Unity 的 MVC 4 模型工厂

标签 asp.net-mvc dependency-injection inversion-of-control unity-container

在我的 MVC 4 项目中,我有一个像这样的模型:

public class MyModel
{
    private readonly IService MyService;

    public MyModel([Dependency]IService service)
    {
        this.MyService = service;
    }
    // ...
}

我的 Controller 有一个像 HttpPost 这样的操作:

[HttpPost]
public ActionResult Show(MyModel myModel)
{
    // do stuff

我的 Controller 没有(也不应该)有我的 IoC 容器的实例。 当 HttpPost 发生并调用操作时,MVC 会在进行模型绑定(bind)时尝试创建我的模型的实例。它需要一个无参数的构造函数来这样做。如果它使用默认构造函数创建一个模型,则不会设置 MyService,并且该模型不会存在所有依赖项。我不想调用 myModel.Init(someIServiceInstance)。我想插入框架,以便在创建模型时解决依赖关系(调用正确的构造函数)。

我目前使用 Unity 作为我的依赖解析器,并有一些工厂用于 Controller 、服务客户端等。对于 Controller ,我能够注册 ControllerFactory 并将依赖项传递到 Controller 中,但我没有看不到我可以注册的 ModelFactory。我不太关心绑定(bind)过程本身;实例化模型后,我对绑定(bind)的完成方式感到满意。我只想实现模型的创建/构造方式。如果 ModelFactory 使用对容器的引用来解决依赖关系,我也可以(我可以将容器注入(inject)工厂作为其构造函数的参数,我只是不希望 Controller 直接引用到容器)。

有没有人有 ModelFactory(或 ModelBinder 和/或 ModelBinderResolver 等)的示例,它将处理模型的创建,然后依赖框架实现来完成其余的绑定(bind)过程?

最佳答案

您可以编写一个自定义模型 Binder :

public class MyModelModelBinder : DefaultModelBinder
{
    protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
    {
        // TODO: create the model instance here using your DI framework or the 
        // DependencyResolver which is more correct
    }
}

然后在您的 Global.asax 中注册此模型绑定(bind)器:

ModelBinders.Binders.Add(typeof(MyModel), new MyModelModelBinder());

但这通常是不好的做法。我建议您使用 View 模型并让您的 Controller 操作将 View 模型作为参数并将 View 模型传递给 View 。这些 View 模型将具有无参数构造函数。然后您可以将域模型或存储库注入(inject)到 Controller 构造函数中。

关于asp.net-mvc - 带有 Unity 的 MVC 4 模型工厂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12958724/

相关文章:

asp.net-mvc - Application_Start不响应RegisterAllAreas()

javascript - 如何在jquery自动完成中添加清除按钮(mvc razor)

flutter - 使用 DI 将 BLoC 作为单例注入(inject)的效果以及在哪里关闭流?

javascript - 这两种声明 AngularJS Controller 的方式有什么区别?

java - Servlet 不应该有可变的实例字段误报 Spring Autowiring (squid :S2226)

Delphi依赖注入(inject): Framework vs Delegating Constructor

javascript - 有没有办法在代码后面访问javascript变量?

asp.net-mvc - 参数字典包含参数的空条目

gwt - Errai体验: user interface,交流,依赖注入(inject)

spring - Spring Autowiring 有什么好处