我即将上线使用 ASP.Net MVC 3 和 Entity Framework 4.1 构建的应用程序。对于依赖注入,我使用了 Unity 2.0 IoC。我使用本教程作为指南来帮助设置 Unity IoC http://weblogs.asp.net/shijuvarghese/archive/2011/01/21/dependency-injection-in-asp-net-mvc-3-using-dependencyresolver -and-controlleractivator.aspx
今天我正在检查我的代码是否有任何最后一分钟的错误修复,并且在我的Global.asax 文件中遇到了 Application_Start()方法。它看起来像这样
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>());
}
该应用程序运行良好,但我注意到我缺少代码行
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
排在后面
IUnityContainer container = new UnityContainer();
正如我所说,没有这行代码,我的应用程序运行良好(无论如何在本地)。我已经添加了它,并且应用程序再次按预期工作。
但是,我有点担心我的 Unity IoC 设置不正确。为什么即使没有这行额外的代码,我的应用程序也能正常工作?我什至需要添加它吗?
谢谢你的帮助。
更新
下面显示了我的一个控制器的构造函数
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;
}