我即将开始使用ASP.Net MVC 3和Entity Framework 4.1构建的应用程序。对于依赖注入,我使用了Unity 2.0 IoC。我用这个教程作为一个指南,以帮助建立统一的IoC http://weblogs.asp.net/shijuvarghese/archive/2011/01/21/dependency-injection-in-asp-net-mvc-3-using-dependencyresolver-and-controlleractivator.aspxASP.Net MVC 3 Unity 2.0 IoC
今天我是通过我的代码检查任何最后一分钟的bug修复和我穿过 的Application_Start()在我的Global.asax文件方法来。它看起来是这样的
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;
}
你可以发布一个控制器的cosnstructor/s吗? – Chandu 2012-07-26 14:49:47
@Chandu当然。请参阅我的更新。 – tgriffiths 2012-07-26 14:52:09
这是你唯一的AccountController构造函数吗? – Chandu 2012-07-26 14:54:14