问题
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