aspnet / Identity

[Archived] ASP.NET Core Identity is the membership system for building ASP.NET Core web applications, including membership, login, and user data. Project moved to https://github.com/aspnet/AspNetCore
Apache License 2.0
1.96k stars 868 forks source link

Create UserManager in Static Class #1776

Closed Pr1vEsc closed 6 years ago

Pr1vEsc commented 6 years ago

I am trying to get a list of Users back from UserManager but I am having issues understanding how this is accomplished.

public class Util { private readonly UserManager _userManager;

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

    public  List<ApplicationUser> GetAllUserList()
    {
        var users = _userManager.Users.ToAsyncEnumerable().ToList().Result;
        return users;
    }

}

However when I create a instance of the Utility class it wants me to pass in a UserManager context and I thought DI would take care of this.

Thoughts Steve

blowdart commented 6 years ago

As UserManager needs a connection to the database, and that's scoped to per request you're not going to be able to do this, even if you did manage to put your utility class in DI.

Remember DI can only inject into other classes in DI.

If all you want this that function why not consider an extension method?

Pr1vEsc commented 6 years ago

I ended up using DI in my Controller and loading the info into a ViewBag and then referencing it in the View.
Thanks for suggestion. Steve

blowdart commented 6 years ago

That would seem the safest way. Whilst you can DI into views, it makes a lot of people who care about purity unhappy :)

Pr1vEsc commented 6 years ago

I did not know you can DI into View. Thanks for the suggestion because that was even easier. Learn new things every day.

@inject UserManager userManager userManager.Users.Select(s=>s.Email)

Much appreciated. Steve