No service for type 'Microsoft.AspNetCore.Identity.SignInManager When - asp.net-core

I am getting
InvalidOperationException: No service for type
'Microsoft.AspNetCore.Identity.SignInManager
1[Authorization.IdentityModels.ApplicationUser]' has been registered.
when I run my ApsCore MVC website.
this are segments from my code:
ConfigureServices:
services.AddDbContext<ApplicationDbContext>(options =>
options.UseNpgsql(configuration["Data:DefaultConnection:ConnectionString"]));
services.AddIdentity<ApplicationUser, IdentityRole<Guid>>()
.AddEntityFrameworkStores<ApplicationDbContext, Guid>()
.AddDefaultTokenProviders();
Configure:
app.UseIdentity();
ApplicationDbContext.cs
public class ApplicationDbContext : IdentityDbContext<ApplicationUser, IdentityRole<Guid>, Guid>
ApplicationUser.cs
public class ApplicationUser : IdentityUser<Guid>
I will be very happy if you can help me.

Faced with the same issue after moving my Identity classes to Guid and found solution here:
You probably need to change your login partial view to use the new
user type IdentityUser
Within Views/Shared/_LoginPartial.cshtml, I just changed
#using Microsoft.AspNetCore.Identity
#inject SignInManager<IdentityUser> SignInManager
#inject UserManager<IdentityUser> UserManager
To
#using Microsoft.AspNetCore.Identity
#inject SignInManager<MyUser> SignInManager
#inject UserManager<MyUser> UserManager
and that worked for me.

Not sure if you are still seeing this issue, but here's some help for anyone else that stumbles upon this. (Note that the specifics are for version 1, but the need for an injected dependency not being available is the same.)
The issue is coming from some class in your application requiring a SignInManager in its constructor, but there isn't an implementation associated with it in the dependency injection setup.
To fix, in your Startup class, in the ConfigureServices method, register the SignInManager class in the services. For example:
services.AddScoped<SignInManager<ApplicationUser>, SignInManager<ApplicationUser>>();
The AddIdentity extension method may have been updated since the original question was asked to add this in, but the same error type will show up for anything the IoC container can't resolve.

This is what worked for me. I had added identity when i was creating the project which made it possible for the framework to inject UserManager<IdentityUser> and SignInManager<IdentityUser> into my _loginPartial View. What i did was to change the Type<TUser> from <IdentityUser> to <ApplicationUser>(ApplicationUser is the identity class i want to use in the project which inherits from IdentityUser class) and everything works fine.

Related

.NET 6 IHubContext Dependency Injection

I'm working on a simple .NET 6 application to enable data update notifications in our front-end application. I've built something similar in .NET 5 before, but I'm running across a DI issue that's got me stumped. In 5, all hubs that were mapped automatically have an IHubContext that is set up in the container for them as well. That doesn't appear to be the case anymore in 6.
System.InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNet.SignalR.IHubContext`1[SignalRNotifications.Hubs.NotificationHub]' while attempting to activate 'SignalRNotifications.Controllers.NotificationController'.
The new non-startup DI in 6 looks weird to me, but I'm just not seeing anything available that says how to fix it. Any suggestions on how to get an IHubContext to inject into my controller?
Thanks!
Update: Here is some pertinent code:
using Microsoft.AspNetCore.Builder;
using SignalRNotifications.Hubs;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddSignalR().AddAzureSignalR();
var app = builder.Build();
// Configure the HTTP request pipeline.
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<NotificationHub>("/NotificationHub");
});
app.Run();
Dependency injection is done in the controller in the most predictable of ways:
namespace SignalRNotifications.Controllers
{
[AllowAnonymous]
[Route("api/[controller]")]
[ApiController]
public class NotificationController : ControllerBase
{
private readonly IHubContext<NotificationHub> _notificationContext;
public NotificationController(IHubContext<NotificationHub> notificationContext)
{
_notificationContext = notificationContext;
}
System.InvalidOperationException: Unable to resolve service for type
'Microsoft.AspNet.SignalR.IHubContext`1[SignalRNotifications.Hubs.NotificationHub]'
while attempting to activate
'SignalRNotifications.Controllers.NotificationController'.
The issue might be related to you having installed the wrong version of SignalR and adding the wrong namespace reference. You are using Microsoft.AspNet.SignalR.IHubContext, instead of Microsoft.AspNetCore.SignalR.IHubContext.
According to your code and refer to the Asp.net Core SignalR document, I create a sample and inject an instance of IHubContext in a controller, everything works well. But I notice that when using the IHubContext, we need to add the using Microsoft.AspNetCore.SignalR; namespace, like this:
So, please check your code and try to use:
using Microsoft.AspNetCore.SignalR;

When scaffolding identity in Blazor Server 6 and overriding IdentityUser, Login and register do not work anymore

Steps to reproduce:
Create new Blazor 6 Server project, with individual account
Updated all Nuget packages to the latest version
Override the default identityuser class (applicationuser) and add some custom properties.
Setup DBContent as following:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
}
Change IdentityUser to ApplicationUser here
Scaffolded identity, so all Razor account views are created.
Add and apply an EF migration, the extra properties are added to the database.
Change startup.cs as following:
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(connectionString));
builder.Services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>();
App runs fine but when I try the register a user, it fails on the following:
I created this test project from scratch, no upgrades. So it created the user (verified in database), but when retrieving it from the database fails.
Logging in with this user also fails with a similar error
Did someone get this working ? Or have some guidance on what I'm doing wrong ?
Thanks !
Well, I found a workaround. I scaffolded identity with the default IdentityUser, then went through all the Identity pages and changed the user class.
That worked.
These properties were nullable (strings) but the new columns were added to the database

How to change the default generic type for AddDefaultIdentity in Asp.net core 2.2

I created a ApplicationUser class that inherits IdentityUser, then in the StartUp class, I changed the services.AddDefaultIdentiy generic type from IdentityUser to ApplicationUser so I can get the service for UserManager<ApplicationUser> instead of UserManager<IdentityUser> .
services.AddDefaultIdentity<ApplicationUser>()
.AddDefaultUI(UIFramework.Bootstrap4)
.AddEntityFrameworkStores<ApplicationDbContext>();
I got this error
InvalidOperationException: No service for type 'Microsoft.AspNetCore.Identity.UserManager`1[Microsoft.AspNetCore.Identity.IdentityUser]' has been registered.
And I can't add two default identity to the service I need help on how to fix this issue
Check that if you change IdentityUser to ApplicationUser in Views\Shared_LoginPartial.cshtml is injected
#inject SignInManager<ApplicationUser> SignInManager
#inject UserManager<ApplicationUser> UserManager

How to resolve dependency inside AuthorizeAttribute with WebApi and Ninject

My current setup is using Ninject for simple IoC, everything goes fine, but I'm not able to resolve one of the classes I need inside my AuthorizeAttribute. I need to access a class that does ClaimsVerification:
Here's my code:
IoC Config:
var kernel = new StandardKernel(); // Ninject IoC
// These registrations are "per instance request".
// See http://blog.bobcravens.com/2010/03/ninject-life-cycle-management-or-scoping/
kernel.Bind<RepositoryFactories>().To<RepositoryFactories>()
.InSingletonScope();
kernel.Bind<IRepositoryProvider>().To<RepositoryProvider>();
kernel.Bind<ISmartDocumentorUow>().To<SmartDocumentorUow>();
kernel.Bind<IClaimsVerification>().To<ClaimsVerification>();
// kernel
//kernel.BindFilter<MyAuthorizeAttribute>(FilterScope.Controller, 0).WhenControllerHas<RequireRolesAttribute>();
// Tell WebApi how to use our Ninject IoC
config.DependencyResolver = new NinjectDependencyResolver(kernel);
MyAuthorizeAttribute:
public class MyAuthorizeAttribute : AuthorizeAttribute
{
[Inject]
IClaimsVerification clamisverify { get; set; }
public MyAuthorizeAttribute()
{
//var x = System.Web.Mvc.DependencyResolver.Current.(typeof(IClaimsVerification));
}
Yap, sorry, the problem was injecting the iClaimsverification that isn't working in web api..
I tryed with the public property and still it didn't work.
the bindfilter is commented out, because it doesn't exist in the core NInject api (dll), it does exists in the MVC dll of ninject but it works for Action filters in the web mvc, and not in the api mvc for what i can tell..
i do solved the issue like this, though i don't like a lot of this fix:
private IClaimsVerification verifier
{
get
{
return (GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(IClaimsVerification)) as IClaimsVerification);
}
}
The property you have marked with Inject is private - you need to initialize Ninject with a custom configuration to opt into what would be a much less efficient process
(You didnt state the problem in your question. I see you were trying BindFilter, but it's commented out (why?) - this is the correct approach. I recommend reading the Ninject.MVC3 wiki article on BindFilter for an example)

How to inject repositories into a custom MembershipProvider?

It seem i can't get this to work. I made a custom MembershipProvider and i want to inject a repository inside but the [Inject] property just doesnt work.
public class PyrosphereMembershipProvider : MembershipProvider
{
[Inject]
protected IDepositoireUtilisateur DepositoireUtilisateur { get; set; }
[Inject]
protected IDepositoireProfile DepositoireProfile { get; set; }
...
I think this is because this class are created way before the MVC application is running which cause the actual problem. I am getting more problem trying to use the membershipprovider than making my own system.
About my ninject configuration i am using the App_Start directory method. All my binding are correct ive looked so that nothing to do with my bindings.
Any help is appreciated!
The ASP.NET Providers aren't designed for proper dependency injection. There are only workarounds for them.
Either you have to setup a binding for them and resolve atleast one instance before using them. E.g. by injecting an instance into the Global.asax or you have to Inject an instance manually before the first use (kernel.Inject(...)). Again most likely in the global.asax application start method.