I am about to go live with an application I have built using ASP.Net MVC 3 and Entity Framework 4.1. For dependency injection I used the Unity 2.0 IoC. I used this tutorial as a guide to help setup the Unity IoC http://weblogs.asp.net/shijuvarghese/archive/2011/01/21/dependency-injection-in-asp-net-mvc-3-using-dependencyresolver-and-controlleractivator.aspx
Today I was checking through my code for any last minute bug fixes and I came across the
Application_Start() method in my Global.asax file. It looks something like this
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
IUnityContainer container = new UnityContainer();
container.RegisterType<IControllerActivator, CustomControllerActivator>(new HttpContextLifetimeManager<IControllerActivator>());
//container.RegisterType<IUnitOfWork, UnitOfWork>(new ContainerControlledLifetimeManager());
container.RegisterType<IUnitOfWork, UnitOfWork>(new HttpContextLifetimeManager<IUnitOfWork>());
container.RegisterType<IListService, ListService>(new HttpContextLifetimeManager<IListService>());
container.RegisterType<IShiftService, ShiftService>(new HttpContextLifetimeManager<IShiftService>());
}
The application is working fine, but I noticed I was missing the line of code
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
Which goes after the line
IUnityContainer container = new UnityContainer();
As I say, my application was working fine (locally anyway) without this line of code. I have since added it and the application is again working as expected.
However, I am a bit worried that my Unity IoC wasn’t setup correctly. Why did my application work even without this additional line of code? And do I even need to add it?
Thanks for your help.
Update
Below shows the constructor for one of my Controllers
public class AccountController : Controller
{
private IAccountService _accountService;
private IUserService _userService;
private IFormsAuthenticationService _formsService;
private INotificationService _notifyService;
private ILoggingService _logService;
public AccountController(ILoggingService logService, IAccountService accountService, IUserService userService, IFormsAuthenticationService formsService, INotificationService notifyService)
{
_accountService = accountService;
_userService = userService;
_formsService = formsService;
_notifyService = notifyService;
_logService = logService;
}
Folks
Please ignore this question. I found out that the line
was included in my code after all.
Note to self – look harder at your code next time!!!