0

I have a problem which(I guess) may be related with api controller.

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

When constructor called userAccountService and authSvc get their values, but in get method authSvc becomes null and userAccountService works as expect.

Thanks.

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
MaxD
  • 254
  • 1
  • 3
  • 14
  • Have you registered your authentication service with your dependency injection container? Does your controller contain a default constructor that doesn't initialize `authSvc`? – Panagiotis Kanavos Dec 08 '14 at 12:28
  • IOC Config http://stackoverflow.com/questions/27292971/membership-reboot-replace-ninject-with-simple-injector – MaxD Dec 08 '14 at 12:29
  • I have no default constructor – MaxD Dec 08 '14 at 12:30
  • @peer this question isn't related to the question you mention as duplicate. The OP knows the field is NULL and asks why this is so in the context of ASP.NET Web API initialization. – Panagiotis Kanavos Dec 08 '14 at 12:30
  • @MaxD then have you registered the service? Which DI container do you use? Can you post its initialization code? – Panagiotis Kanavos Dec 08 '14 at 12:31
  • @Panagiotis Kanavos - http://stackoverflow.com/questions/27292971/membership-reboot-replace-ninject-with-simple-injector – MaxD Dec 08 '14 at 12:32
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/66399/discussion-between-maxd-and-panagiotis-kanavos). – MaxD Dec 08 '14 at 12:35

1 Answers1

3

Here:

public AccountController(AuthenticationService<HierarchicalUserAccount> authSvc)
{
    authSvc = authSvc;
    userAccountService = authSvc.UserAccountService;
}

You are assigning the local variable authSvc back to itself. You want to assign the class-level field:

public AccountController(AuthenticationService<HierarchicalUserAccount> authSvc)
{
    this.authSvc = authSvc;
    userAccountService = authSvc.UserAccountService;
}

You can avoid this confusion in future by using proper naming conventions (prefix private fields with an underscore).

private readonly AuthenticationService<HierarchicalUserAccount> _authSvc;
Ant P
  • 24,820
  • 5
  • 68
  • 105