2
votes

I am converting an existing Asp.net Mvc project to .Net Core now the issue is this get method

public ApplicationUserManager UserManager
    {
        get
        {



return _userManager ??
HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();

        }
        private set
        {
            _userManager = value;
        }
    }

In Mvc we could fetch OwinContext using

HttpContext.GetOwinContext().GetUserManager()

but in case of .Net Core GetOwinContext not present , When I compare definition of HttpContext of both classes enter image description here

enter image description here

HttpContextBase is type in case of Mvc but in case of Core there is HttpContext which has no extension method in same namespace as HttpContextBase that's why this extension method was not found ,Please let me know how to do this in Core?

enter image description here

2
Just use dependency injection instead. docs.microsoft.com/en-us/aspnet/core/fundamentals/…Tseng
then please let me know how to inject this as dependency?TAHA SULTAN TEMURI

2 Answers

4
votes

There is no alternate. ASP.NET Core uses dependency injection for pretty much everything. If you need UserManager<TUser>, you inject into the constructor of whatever class you're working with (controller, etc.):

public class MyController : Controller
{
    private readonly UserManager<ApplicationUser> _userManager;

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

    ...
}
2
votes

For accessing UserManager from HttpContext, you could try to implement an extension like below:

public static class HttpContextExtension
{
    public static UserManager<TUser> GetUserManager<TUser>(this HttpContext context) where TUser: class
    {
        return context.RequestServices.GetRequiredService<UserManager<TUser>>();
    }
}

And then use it like

public class HomeController : Controller
{        
    public IActionResult Index()
    {
        var userManager = HttpContext.GetUserManager<IdentityUser>();
        return View();
    }       
}