Nicefsf
Nicefsf

Reputation: 140

Get user manager at extension class

I'm migrating my ASP.net MVC project to core version. I have an extension class with method, that returns user's name by user id (Guid).

public static class IdentityHelpers
{
    public static MvcHtmlString GetUserName(this HtmlHelper html, string id)
    {
        var manager = HttpContext.Current
            .GetOwinContext().GetUserManager<AppUserManager>();

        return new MvcHtmlString(manager.FindByIdAsync(id).Result.UserName);
    }
}

As I'm rewriting this to .NET Core, I don't know how to get user manager instance here. Normally I would just inject this through DI, but I don't know what to do as I'm using extension method so I can't inject it.

How can I get UserManager in static class?

Upvotes: 1

Views: 525

Answers (1)

Nkosi
Nkosi

Reputation: 247018

Things have changed in the new version. Access the current HttpContext via the HtmlHelper.ViewContext and from there you should be able to get access to an IServiceProvider that can be used to resolve services.

public static class IdentityHelpers {
    public static MvcHtmlString GetUserName(this HtmlHelper html, string id) {
        HttpContext context = html.ViewContext.HttpContext;
        IServiceProvider services = context.RequestServices;
        var manager = services.GetService<AppUserManager>();

        return new MvcHtmlString(manager.FindByIdAsync(id).Result.UserName);
    }
}

Upvotes: 1

Related Questions