I am trying to build new website with ASP.NET Core 1 (May 2016), and I need to implement different kind of sign-in procedures (not with SQL Server).
So I am trying implement MyOwnUserStore
, where I want to override login procedures, but when I start the application the result is this exception:
InvalidOperationException: Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContext' while attempting to activate 'LoginWebApp04.Services.MyOwnUserStore'.
My code is simple, new class:
public class MyOwnUserStore : UserStore<ApplicationUser>
{
public MyOwnUserStore(DbContext context, IdentityErrorDescriber describer = null)
: base(context, describer)
{
}
...
}
and modification of Startup.cs
:
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
var idt = services.AddIdentity<ApplicationUser, IdentityRole>();
idt.AddUserStore<MyOwnUserStore>(); // <-------------------------- HERE
idt.AddEntityFrameworkStores<ApplicationDbContext>();
idt.AddDefaultTokenProviders();
services.AddMvc();
// Add application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
}
I have changed nothing else in my new project, and the project is created as ASP.NET Core Web Application with authentication = individual user accounts.
So what I need to do more to make the first run of my app without exception?
I have tried many examples from internet but all I have found are outdated.
The DI framework doesn't know what to resolve for the user store. Change DbContext
in the constructor to ApplicationDbContext
public class MyOwnUserStore : UserStore<ApplicationUser> {
public MyOwnUserStore(ApplicationDbContext context, IdentityErrorDescriber describer = null)
: base(context, describer) {
}
...
}
Change the order of when you add the user store. You need to add entity framework stored before adding user store.
public void ConfigureServices(IServiceCollection services) {
// Add framework services.
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services
.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddUserStore<MyOwnUserStore>() // <----MOVED AFTER ADDING EF STORES
.AddDefaultTokenProviders();
services.AddMvc();
// Add application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With