如何在 ASP.NET MVC 2+ 中使用带有模型绑定器的 DI/IoC 容器? [英] How to use a DI / IoC container with the model binder in ASP.NET MVC 2+?

本文介绍了如何在 ASP.NET MVC 2+ 中使用带有模型绑定器的 DI/IoC 容器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个 User 实体,我想在构造函数中将它的 CreationTime 属性设置为 DateTime.Now.但作为单元测试采用者,我不想直接访问 DateTime.Now,而是使用 ITimeProvider :

Let's say I have an User entity and I would want to set it's CreationTime property in the constructor to DateTime.Now. But being a unit test adopter I don't want to access DateTime.Now directly but use an ITimeProvider :

public class User {
    public User(ITimeProvider timeProvider) {
        // ...
        this.CreationTime = timeProvider.Now;
    }

    // .....
}

public interface ITimeProvider { 
    public DateTime Now { get; }
}

public class TimeProvider : ITimeProvider {
    public DateTime Now { get { return DateTime.Now; } }
}

我在我的 ASP.NET MVC 2.0 应用程序中使用 NInject 2.我有一个 UserController 和两个 Create 方法(一个用于 GET,一个用于 POST).GET 的一个是直截了当的,但 POST 的那个不是那么直,也不是那么向前:P 因为我需要弄乱模型绑定器来告诉它获取 ITimeProvider 实现的参考,以便能够构造一个用户实例.

I am using NInject 2 in my ASP.NET MVC 2.0 application. I have a UserController and two Create methods (one for GET and one for POST). The one for GET is straight forward but the one for POST is not so straight and not so forward :P because I need to mess with the model binder to tell it to get a reference of an implementation of ITimeProvider in order to be able to construct an user instance.

public class UserController : Controller {

    [HttpGet]
    public ViewResult Create() {
         return View();
    }

    [HttpPost]
    public ActionResult Create(User user) {

         // ...

    }
}

我还希望能够保留默认模型绑定器的所有功能.

I would also like to be able to keep all the features of the default model binder.

有机会解决这个简单/优雅/等问题吗?:D

Any chance to solve this simple/elegant/etc? :D

推荐答案

试试这个:

public class User 
{
    public Func<DateTime> DateTimeProvider = () => DateTime.Now;

    public User() 
    {
        this.CreationTime = DateTimeProvider();
    }
}

在你的单元测试中:

var user = new User();
user.DateTimeProvider = () => new DateTime(2010, 5, 24);

我知道这不是很优雅,但不是弄乱模型绑定器,这可能是一个解决方案.如果这不是一个好的解决方案,您可以实现自定义模型绑定器并覆盖 CreateModel 方法,您可以在该方法中将依赖项注入模型的构造函数中.

I know that this is not very elegant but instead of messing with the model binder this could be a solution. If this doesn't feel like a good solution you could implement a custom model binder and override the CreateModel method where you would inject the dependencies in the constructor of the model.

这篇关于如何在 ASP.NET MVC 2+ 中使用带有模型绑定器的 DI/IoC 容器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆