我有一个问题(我猜)可能与api控制器有关。
public class AccountController : ApiController
{
private readonly UserAccountService<HierarchicalUserAccount> userAccountService;
private readonly AuthenticationService<HierarchicalUserAccount> authSvc;
public AccountController(AuthenticationService<HierarchicalUserAccount> authSvc)
{
authSvc = authSvc;
userAccountService = authSvc.UserAccountService;
}
[HttpGet]
public async Task<HttpResponseMessage> Get()
{
...
HierarchicalUserAccount account;
if (userAccountService.AuthenticateWithUsernameOrEmail("name@mail.com", "123456", out account))
{
authSvc.SignIn(account, false); //ERROR because authSvc is null
}
return await ... ;
}
当构造函数userAccountService和authSvc获取它们的值时,但在get方法中,authSvc变为null,userAccountService按预期工作。
感谢。
答案 0 :(得分:3)
下面:
public AccountController(AuthenticationService<HierarchicalUserAccount> authSvc)
{
authSvc = authSvc;
userAccountService = authSvc.UserAccountService;
}
您正在将本地变量 authSvc
分配回自身。您想要分配类级别字段:
public AccountController(AuthenticationService<HierarchicalUserAccount> authSvc)
{
this.authSvc = authSvc;
userAccountService = authSvc.UserAccountService;
}
通过使用适当的命名约定(前缀为带有下划线的私有字段),您可以避免这种混淆。
private readonly AuthenticationService<HierarchicalUserAccount> _authSvc;