Reputation: 2623
I am trying to use LightInject with my current project but I keep getting a null value. I have a web app in MVC 5 and a business tier attached with it. I have installed the LightInject.Mvc and LightInject.Web in my web project. I have installed the LightInject.Mvc in my business project.
In the business tier, I have a compositionRoot.cs file:
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>();
}
}
}
Next, in the web project, in the Global.asax.cs, I have the following in the app_start method:
var serviceContainer = new ServiceContainer();
serviceContainer.RegisterFrom<Business.CompositeRoot>();
serviceContainer.EnableMvc();
Finally, my controller code looks like this:
public class AccountController : Controller
{
public IRegisterUserCommand RegisterUserCommand { get; set; }
[HttpGet]
[AllowAnonymous]
public ActionResult Login()
{
RegisterUserCommand.Execute();
return View();
}
}
I basically get the null exception in the controller when the code is trying to use RegisterUserCommand. I assumed that LightInject automatically injected code when an interface is encountered. What am I missing?
Upvotes: 0
Views: 524
Reputation: 2623
I figured it out after looking at the code for LigtInject.Mvc project. Basically, the code in my global.asax.cs should look like below:
var serviceContainer = new ServiceContainer();
serviceContainer.RegisterFrom<Business.CompositeRoot>();
serviceContainer.RegisterControllers();
serviceContainer.EnableMvc()
Upvotes: 0