Dependency Injection of a service usage inside the global.asax

走远了吗. 提交于 2019-12-07 18:41:44

问题


I'm using Ninject to do dependency injection. I have a userService in which I need to access from the global.asax file.

How do I dependency inject this?

    private IUserService userService;//<--this
    protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
    {
        HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
        if (authCookie != null)
        {
            FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
            var identity = new CustomIdentity(authTicket);
            string[] userRoles = userService.GetRolesForUser(identity.Name);// <-- Used here.
            var principal = new GenericPrincipal(identity, userRoles);
            Context.User = principal;
        }
    }

I did my bindings in another file(NinjectMVC3) using the WebActivator. Which was created by the nuget package.


回答1:


Instead of injection try to resolve in your method...

protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
{
  var userService = DependencyResolver.Current.GetService<IUserService>();
  ...
}

Don't forget to set dependency resolver to Ninject's implementation before use, for example in your NinjectMVC3 (WebActivator) file.

DependencyResolver.SetResolver(new NinjectDependencyResolver( ... ));


来源:https://stackoverflow.com/questions/6218417/dependency-injection-of-a-service-usage-inside-the-global-asax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!