【问题标题】:ASP.NET MVC 5 and LightInjectASP.NET MVC 5 和 LightInject
【发布时间】:2016-10-20 15:36:00
【问题描述】:

我正在尝试在我当前的项目中使用 LightInject,但我一直得到一个空值。我在 MVC 5 中有一个 Web 应用程序,并附有一个业务层。我已经在我的网络项目中安装了 LightInject.MvcLightInject.Web。我已经在我的业务项目中安装了 LightInject.Mvc

在业务层,我有一个 compositionRoot.cs 文件:

using LightInject;
using SimpleKB.Business.Commands;

namespace SimpleKB.Business
{
    public class CompositeRoot : ICompositionRoot
    {
        public void Compose(IServiceRegistry serviceRegistry)
        {
            serviceRegistry.Register<IRegisterUserCommand, RegisterUserCommand>();
            serviceRegistry.Register<ICreateCategoryCommand, CreateCategoryCommand>();
            serviceRegistry.Register<IUpdateCategoryCommand, UpdateCategoryCommand>();
        }
    }
}

接下来,在 web 项目中,在 Global.asax.cs 中,我在 app_start 方法中有以下内容:

var serviceContainer = new ServiceContainer();
serviceContainer.RegisterFrom<Business.CompositeRoot>();
serviceContainer.EnableMvc();

最后,我的控制器代码如下所示:

public class AccountController : Controller
    {
        public IRegisterUserCommand RegisterUserCommand { get; set; }

        [HttpGet]
        [AllowAnonymous]
        public ActionResult Login()
        {
            RegisterUserCommand.Execute();
            return View();
        }
    }

当代码尝试使用 RegisterUserCommand 时,我基本上在控制器中得到了 null 异常。我假设 LightInject 在遇到接口时会自动注入代码。我错过了什么?

【问题讨论】:

    标签: asp.net-mvc-5 light-inject


    【解决方案1】:

    我在查看 LigtInject.Mvc 项目的代码后发现了这一点。基本上,我的 global.asax.cs 中的代码应该如下所示:

    var serviceContainer = new ServiceContainer();
    serviceContainer.RegisterFrom<Business.CompositeRoot>();
    serviceContainer.RegisterControllers();
    serviceContainer.EnableMvc()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-27
      • 2018-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-04
      • 2016-03-24
      相关资源
      最近更新 更多