在Global.asax内的服务使用依赖注入 [英] Dependency Injection of a service usage inside the global.asax

查看:550
本文介绍了在Global.asax内的服务使用依赖注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Ninject做的依赖注入。我有一个userService中,我需要从Global.asax文件访问。

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

我如何依赖注入呢?

    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;
        }
    }

我使用 WebActivator 做我绑定在另一个​​文件( NinjectMVC3 )。这是由包的NuGet创建。

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

推荐答案

尝试在你的方法来解决...

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

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

不要忘了依赖解析器设置为使用前Ninject的实现,例如在你的NinjectMVC3(WebActivator)文件。

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

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

这篇关于在Global.asax内的服务使用依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆