5

I am trying to create an instance of UserManager in Mvc Core 2 as I did on ASP.NET MVC 6 with following code:

var UserManager = new UserManager<DbUser>(new UserStore<DbUser>(this) );

I receive many errors according to missing parameters, Is there a proper way of getting the instance outside of the controller?

2
  • Do you start with a new application or are you trying migration? Is it not possible to let it inject bi DI Framework like public YourClass(IUserManager userManager) { ... You need also the right configuration for it... Commented Mar 23, 2018 at 14:10
  • Yes, I was able to get it from DI, but I am spouse to seed few admin users in starting the application,Yet the seed method was inside DbContext which was in another assembly and I did not have access to DI Commented Mar 23, 2018 at 15:16

1 Answer 1

4

I did not have access to DI.

this explanation is incorrect, you can inject UserManager in another assembly read more.

Just create a service for seeding your data for example:

public interface IInitializationService
{
    void Seed();
}

public class InitializationService : IInitializationService
{
    private readonly UserManager<ApplicationUser> _userManager;

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

    public void Seed()
    {
        // more code
    }
}

Register service in Startup.cs

 public void ConfigureServices(IServiceCollection services)
 {
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));

        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

        services.AddTransient<IInitializationService, InitializationService>();

        services.AddMvc();
 }

 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
 {
        // more code ...

        var scopeFactory = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>();
        using (var scope = scopeFactory.CreateScope())
        {
            var identityDbInitialize = scope.ServiceProvider.GetService<IInitializationService>();
            identityDbInitialize.Seed();
        }

      // more code ...
 }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.