I am attempting to inject a UserFactory via Ninject, here is my binding:
var u = new CurrentUserProvider(HttpContext.Current);
kernel.Bind<ICurrentUserProvider>().ToMethod(context => u).InRequestScope();
This factory uses HttpContext
to read a authentication cookie and populate a CurrentUser
object, HttpContext is passed as a constructor parameter:
public class CurrentUserProvider : ICurrentUserProvider
{
public ICurrentUser CurrentUser { get; set; }
public CurrentUserProvider(HttpContext context)
{
CurrentUser = GetCurrentUser(context);
}
private static ICurrentUser GetCurrentUser(HttpContext ctx)
{
var httpCookie = ctx.Request.Cookies[".ASPXAUTH"];
if (httpCookie != null)
{
var cookie = httpCookie.Value;
var ticket = FormsAuthentication.Decrypt(cookie);
if (ticket != null)
{
var x = ticket.UserData.FromJson<CurrentUser>();
ctx.Session["UserID"] = x.DatabaseName;
return x;
}
}
return null;
}
}
However the HttpContext that gets passed into the UserFactory constructor is always null. This is a MVC4 project if that makes any difference to the approach.
Update:
I have also tried the following code which does not error but my injected CurrentUserProvider
property remains null:
kernel.Bind<ICurrentUserProvider>().To<CurrentUserProvider>().InRequestScope()
.WithConstructorArgument("context", ninjectContext => HttpContext.Current);