AuthenticationManager HttpContext为Null

时间:2014-07-03 12:00:15

标签: c# asp.net asp.net-mvc-5 ninject

我试图在我的控制器中使用此代码:

IAccountManagementService<User> _service;
public AccountController(IAccountManagementService<User> service)
{
    _service = service;
    _service.AuthenticationManager = HttpContext.GetOwinContext().Authentication;
    _service.UserManager = new UserManager<User>(new UserStore<User>(new DefaultContext()));
}

它已经从ASP.NET MVC 5模板的原始样板代码中略微改编

它通过Ninject注入,Ninject正在使用依赖解析器和模块加载器:

var kernel = new StandardKernel(new ModuleLoader());

DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));

所以我不知道这是否会扰乱上下文。

该服务只是将原始代码抽象出来,服务如下:

IRepository _repository;
public AccountManagementService(IRepository repository)
{
    _repository = repository;
}

public UserManager<User> UserManager { get; set; }
public IAuthenticationManager AuthenticationManager { get; set; }
public RoleManager<IdentityRole> RoleManager { get; set; }

原始代码如下所示:

public AccountController()
            : this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())))
{
}

public AccountController(UserManager<ApplicationUser> userManager)
{
    UserManager = userManager;
}

public UserManager<ApplicationUser> UserManager { get; private set; }

private IAuthenticationManager AuthenticationManager
{
    get
    {
        return HttpContext.GetOwinContext().Authentication;
    }
}

我可能会注射IAuthenticationManager,但还没有正确地调查它。

我只是不确定当我加载我的网站时,我点击登录,它将我带到控制器的构造函数并指向开始的行:_service.AuthenticationManager并告诉我HttpContext 1}}为空。

1 个答案:

答案 0 :(得分:1)

我通过重新执行所有Ninject依赖注入来修复此问题。我现在正在遵循Ninject MVC 5的惯例

我为ASP.NET Identity添加了这些绑定:

//<----- ACCOUNT STUFF ----->\\
kernel.Bind<IUserStore<EbpUser>>().To<UserStore<EbpUser>>().WithConstructorArgument("context", context => kernel.Get<DefaultContext>());
kernel.Bind<IRoleStore<IdentityRole, string>>().To<RoleStore<IdentityRole, string, IdentityUserRole>>().WithConstructorArgument("context", context => kernel.Get<DefaultContext>());

然后获取HttpContext绑定AuthenticationManager

kernel.Bind<IAuthenticationManager>().ToMethod(c => HttpContext.Current.GetOwinContext().Authentication).InRequestScope();

AccountManagementService内,我现在就这样做:

IRepository _repository;
IAuthenticationManager _authManager;
UserManager<EbpUser> _userManager;
RoleManager<IdentityRole> _roleManager;

public AccountManagementService(IRepository repository, IUserStore<EbpUser> userStore, IRoleStore<IdentityRole, string> roleStore, IAuthenticationManager authManager)
{
    _repository = repository;
    _authManager = authManager;
    _userManager = new UserManager<EbpUser>(userStore);
    _roleManager = new RoleManager<IdentityRole>(roleStore);
}

所以现在所有注入的东西都看起来很整洁。

相关问题