Ninject-ing a dependency in Global.asax

前端 未结 4 592
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-29 11:56

I\'m starting a web application with MVC3 and Ninject. There is one dependency that I also need in the Global.asax file that needs to be a singleton.

I thought it sh

4条回答
  •  借酒劲吻你
    2020-12-29 12:40

    This is how we do it, I did some testing and my AuthService seems to go in his controller only once :

    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().To().InRequestScope();
                kernel.Bind().To().InSingletonScope();
                kernel.Bind().To().InRequestScope();
                kernel.Bind().To().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;
                            }
                        }
                    }
                }
            }
    }
    

    Hope it helps!

提交回复
热议问题