简体   繁体   中英

Owin Context on Asp .Net Identity

I've confused over how this code from asp .net identity template being implemented.

private ApplicationSignInManager _signInManager;
private ApplicationUserManager _userManager;
private ApplicationRoleManager _roleManager;

public AuthController() { }

public AuthController(ApplicationUserManager userManager, ApplicationSignInManager signInManager, ApplicationRoleManager roleManager)
{
    UserManager = userManager;
    SignInManager = signInManager;
    RoleManager = roleManager;
}

public ApplicationRoleManager RoleManager
{
    get { return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>(); }
    private set { _roleManager = value; }
}

public ApplicationSignInManager SignInManager
{
    get { return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>(); }
    private set { _signInManager = value; }
}

public ApplicationUserManager UserManager
{
    get { return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>(); }
    private set { _userManager = value; }
} 

Why we have the AuthController with parameter? Depedency Injection purpose? And if no injection happen then called the owincontext that being specified on Startup.cs ? Are this means we can ignore the owincontext and use the injection only?

And when i tried to debug how this is running, it's only through the parameterless constructor and it breaks my code. Are this parametered constructor not used?

Any idea? Thanks.

Indeed this template is for working with DI container and without one - to cover all cases. As you said - if DI is used, constructor with parameters is used.

And if nothing was provided in constructor, then reach into OWIN and get instances of required objects.

Yes, if you are a using DI, you can remove properties with HttpContext.GetOwinContext() and just leave constructor with parameters.

If you are using DI, but controller is created via parameterless constructor, then you don't have DependencyResolver configured for Asp.Net. In Global.asax.cs (or wherever you do DI configuration) you need to call DependencyResolver.SetResolver(myContainerWrapper); where myContainerWrapper is IDependencyResolver and you need look up how your DI container is integrating with Asp.Net.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM