Asp.net-Mvc
在 Global.asax 中註入依賴項
我正在使用 MVC3 和 Ninject 啟動一個 Web 應用程序。在 Global.asax 文件中我還需要一個依賴項,它需要是一個單例。
我認為它應該是這樣的:
public class MvcApplication : NinjectHttpApplication { IUserAuthentication _auth; public MvcApplication() { base.AuthenticateRequest += new EventHandler(MvcApplication_AuthenticateRequest); } protected override IKernel CreateKernel() { var _kernel = new StandardKernel(new SecurityModule()); _auth = _kernel.Get<IUserAuthentication>(); return _kernel; } void MvcApplication_AuthenticateRequest(object sender, EventArgs e) { _auth.ToString(); }但是後來我看到它在被呼叫
_auth時為空MvcApplication_AuthenticateRequest。然後我嘗試這樣:
public class MvcApplication : NinjectHttpApplication { ItUserAuthentication _auth; IKernel _kernel; public MvcApplication() { _kernel = new StandardKernel(new SecurityModule()); _auth = _kernel.Get<IUserAuthentication>(); base.AuthenticateRequest += new EventHandler(MvcApplication_AuthenticateRequest); } protected override IKernel CreateKernel() { return _kernel; } void MvcApplication_AuthenticateRequest(object sender, EventArgs e) { _auth.ToString(); }但是現在我可以看到建構子被多次呼叫,因此我將有幾個 IKernel,我猜單例實例在我的應用程序範圍內不會那麼單例。
我該怎麼做?使用靜態變數?
我們就是這樣做的,我做了一些測試,我的 AuthService 似乎只進入了他的控制器一次:
public class MvcApplication : NinjectHttpApplication { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); } protected override IKernel CreateKernel() { var kernel = new StandardKernel(); kernel.Load(Assembly.GetExecutingAssembly()); kernel.Bind<ISession>().To<MongoSession>().InRequestScope(); kernel.Bind<IAuthenticationService>().To<AuthenticationService>().InSingletonScope(); kernel.Bind<IMailer>().To<Mailer>().InRequestScope(); kernel.Bind<IFileProvider>().To<MongoFileProvider>().InRequestScope(); return kernel; } protected override void OnApplicationStarted() { base.OnApplicationStarted(); AreaRegistration.RegisterAllAreas(); RegisterRoutes(RouteTable.Routes); } protected void Application_AuthenticateRequest(Object sender, EventArgs e) { if (HttpContext.Current.User != null) { if (HttpContext.Current.User.Identity.IsAuthenticated) { if (HttpContext.Current.User.Identity is FormsIdentity) { var id = (FormsIdentity) HttpContext.Current.User.Identity; var ticket = id.Ticket; var authToken = ticket.UserData; var authService = (IAuthenticationService)DependencyResolver.Current.GetService(typeof(IAuthenticationService)); var user = authService.GetUserForAuthToken(authToken); if (user != null) { user.SetIdentity(HttpContext.Current.User.Identity); HttpContext.Current.User = (IPrincipal) user; } } } } } }希望能幫助到你!