2016-10-20 111 views
0

我想使用LightInject與我當前的項目,但我一直得到一個空值。我在MVC 5中有一個Web應用程序,並附帶了一個業務層。我已在我的Web項目中安裝了LightInject.MvcLightInject.Web。我在我的商業項目中安裝了LightInject.MvcASP.NET MVC 5和LightInject

在業務層,我有一個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。我認爲LightInject在遇到接口時會自動注入代碼。我錯過了什麼?

回答

0

我看了LigtInject.Mvc項目的代碼後發現它。基本上,我的global.asax.cs中的代碼應該如下所示:

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