我即將開始使用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