1

鉴于此代码:

namespace Eisk.Controllers
{
    public class EmployeesController : Controller
    {
        DatabaseContext _dbContext;

        public EmployeesController(DatabaseContext databaseContext)
        {
            _dbContext = databaseContext;
        }

        public ViewResult Index()
        {
            var employees = _dbContext.EmployeeRepository;

            return View(employees.ToArray());
        }

请注意,构造函数不会新建数据库。

当从单元测试访问时,我可以注入一个 databaseContext,控制器将在测试期间使用它。我无法弄清楚的是这段代码在哪里获取它在运行时使用的数据库上下文。如果我能发现这一点,我也许能够弄清楚如何规避这种行为并让它使用模拟/内存数据库。

更多解释:我现在无法访问此应用程序的旧数据库,所以我试图模拟一个从 xml 文件填充的内存数据源。这就是为什么我需要能够规避默认的数据库上下文创建。

更多信息:感谢您迄今为止所提供的所有帮助,你们这些很棒的人。

史蒂文似乎指引我走上了正确的道路。在 Global.asax 文件中是这个调用:

DependencyInjectorInitializer.Init();

之后通过我得到的代码:

        public static void Initialize()
    {
        _container = new UnityContainerFactory().CreateConfiguredContainer();     
        var serviceLocator = new UnityServiceLocator(_container);
        ServiceLocator.SetLocatorProvider(() => serviceLocator);
        DependencyResolver.SetResolver(new UnityDependencyResolver(_container));
    }

至少这让我朝着正确的方向前进。现在我必须弄清楚 Unity 是如何创建上下文的,这样我才能进行干预。

  • 让我在这里插入 EISK MVC Employee Info Starter Kit。这是 Mohammad Ashraful Alam 等人开发的经过深思熟虑的系统。其中包括一个成熟的例子,说明有多少新技术可以结合在一起。MVC 5、Entity Framework 6、Unity、身份验证、OpenAuth、DI、Moq 和其他一些东西。可用作模板、一般学习或培训。 员工信息入门套件
4

1 回答 1

3

使用 ASP.NET MVC 的默认配置,控制器应该有一个默认构造函数(即没有参数的公共构造函数)。如果不是 ASP.NET MVC 将抛出以下异常:

类型“Eisk.Controllers.EmployeesController”没有默认构造函数

If this however works, this means that you (or another developer) overwrote the default configuration by either using a custom IControllerFactory or custom IDependencyResolver. Most developers do this by using an open source Dependency Injection library (such as Simple Injector, Autofac or Castle Windsor). If you pull in the NuGet MVC integration packages for such library, it will usually do this configuration for you. So somebody on your team might have done this for you.

My advice is: talk to your team and ask them how they did this and which container they used and where you can find the configuration for that.

于 2014-11-27T09:10:26.183 回答