working with IdentityCore and cant create migration with AddDefaultTokenProviders method.
Error -
An error occurred while accessing the Microsoft.Extensions.Hosting services. Continuing without the application service provider. Error: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType:
Microsoft.AspNetCore.Identity.DataProtectorTokenProvider`1[server.Domain.Models.IdentityUser] Lifetime: Transient ImplementationType:
Microsoft.AspNetCore.Identity.DataProtectorTokenProvider`1[server.Domain.Models.IdentityUser]': Unable to resolve service for type
'Microsoft.AspNetCore.DataProtection.IDataProtectionProvider' while attempting to activate 'Microsoft.AspNetCore.Identity.DataProtectorTokenProvider`1[server.Domain.Models.IdentityUser]'.)
Identity system and db configuration -
builder.Services.AddEntityFrameworkNpgsql()
.AddDbContext<AppDbContext>(opt =>
opt.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddIdentityCore<IdentityUser>()
.AddUserManager<UserManager<IdentityUser>>()
.AddEntityFrameworkStores<AppDbContext>()
.AddDefaultTokenProviders();
public class AppDbContext : IdentityDbContext<IdentityUser>
{
public AppDbContext(DbContextOptions<AppDbContext> opt) : base(opt)
{}
}
Related
I try to connect to a MySql database with .net core.
I was previously connecting to a sql server database and it was working well.
But now I got the following error message in program.cs on line :
var app = builder.Build();
Error while validating the service descriptor 'ServiceType: PatrimoineClick.Data.DbInitializer Lifetime: Transient ImplementationType: PatrimoineClick.Data.DbInitializer': Unable to resolve service for type 'PatrimoineClick.Data.PatrimoineClickDbContext' while attempting to activate 'PatrimoineClick.Data.DbInitializer'.
Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: PatrimoineClick.Data.DbInitializer Lifetime: Transient ImplementationType: PatrimoineClick.Data.DbInitializer': Unable to resolve service for type 'PatrimoineClick.Data.PatrimoineClickDbContext' while attempting to activate 'PatrimoineClick.Data.DbInitializer'.) (Error while validating the service descriptor 'ServiceType: PatrimoineClick.Areas.General.Traitement Lifetime: Scoped ImplementationType: PatrimoineClick.Areas.General.Traitement': Unable to resolve service for type 'PatrimoineClick.Data.PatrimoineClickDbContext' while attempting to activate 'PatrimoineClick.Areas.General.Traitement'.)
I add the db context like this :
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
//builder.Services.AddDbContext<ApplicationDbContext>(options =>
// options.UseSqlServer(connectionString));
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseMySQL(connectionString));
The connectionString "DefaultConnection" is :
"DefaultConnection": "server=127.0.0.1;port=3306;user=root;database=PatrimoineClick"
I'm using a XAMPP server with default configuration :
No password for user root.
I don't understand why the service is not created.
Thanks by advance,
I don't understand why the service is not created.
It would be nicer if you could include your DbContext class as well. However, the error telling us it faild to construct PatrimoineClick.Data.DbInitializer
Means, you might not intialize it in your program.cs or you may not construct your options.UseMySQL on OnConfiguring. Roughly, you need to include below code snippet inside your ApplicationDbContext
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseMySql(#"server=127.0.0.1;port=3306;user=root;database=PatrimoineClick");
}
Note: It would be great if you could try to with password. Sometime, password might cause the issue based on the configuration of your MySql server, Thus, you can try this pattern as well "server=localhost;port=3305;database=parking;uid=root"
Full Application DbContext:
public class ApplicationDbContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseMySql(#"server=127.0.0.1;port=3306;user=root;database=PatrimoineClick");
}
}
Or you can also try below format as well:
public class ApplicationDbContext : DbContext
{
public DbSet<User> User { get; set; }
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { }
}
You can check this official document
In addition, please make sure you have added, below nuget package while adding mySql DB
dotnet add package Pomelo.EntityFrameworkCore.MySql --version 6.0.2
You can download it from this official link Or you can even add it from your visual studio nuget package manager as below:
Update Program.cs:
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<ApplicationDbContext>(options => {
options.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString));
});
builder.Services.AddTransient<DbInitializer>(); Or
builder.Services.AddTransient<IDbInitializer,DbInitializer>();
and
builder.Services.AddScoped<ITraitement, Traitement>();
If DbInitializer has the type Interface IDbInitializer. You can check the dependency injection official document here
I could not find answer that would resolve my issue. I'm getting 2 exceptions in my minimal API:
1: System.AggregateException
Some services are not able to be constructed (Error while validating
the service descriptor 'ServiceType: MinApiEFCore.Data.ConnectRepo
Lifetime: Singleton ImplementationType:
MinApiEFCore.Data.ConnectRepo': Unable to resolve service for type
'DocuWare.Platform.ServerClient.ServiceConnection' while attempting to
activate 'MinApiEFCore.Data.ConnectRepo'.) (Error while validating
the service descriptor 'ServiceType: MinApiEFCore.Data.IConnectRepo
Lifetime: Scoped ImplementationType: MinApiEFCore.Data.ConnectRepo':
Unable to resolve service for type
'DocuWare.Platform.ServerClient.ServiceConnection' while attempting to
activate 'MinApiEFCore.Data.ConnectRepo'.)'
2: InvalidOperationException
Unable to resolve service for type
'DocuWare.Platform.ServerClient.ServiceConnection' while attempting to
activate 'MinApiEFCore.Data.ConnectRepo'.
"ServiceConnection" is from an "external" class from DocuWare (via NuGet) used for creating a connection.
My IConnectRepo interface looks like this:
public interface IConnectRepo
{
ServiceConnection CreateServiceConnectionAsync(Uri uri, string user, string password);
}
ConnectRepo class:
public class ConnectRepo : IConnectRepo
{
private ServiceConnection _serviceConnection;
public ConnectRepo(ServiceConnection serviceConnection)
{
_serviceConnection = serviceConnection;
}
public ServiceConnection CreateServiceConnectionAsync(Uri uri, string user, string password)
{
//Organizations == null means I am not connected
if (_serviceConnection.Organizations.FirstOrDefault() == null)
{
_serviceConnection = ServiceConnection.Create(uri, user, password);
}
return _serviceConnection;
}
}
Program.cs
..
builder.Services.AddScoped<IConnectRepo, ConnectRepo>();
..
Still not sure why I cannot inject ServiceConnection in the constructor. Any help would be appreciated.
You cannot inject ServiceConnection as it has not been added to DI container. You can register the service like following...
..
builder.Services.AddScoped<IConnectRepo, ConnectRepo>();
builder.Services.AddScoped<ServiceConnection>();
..
...but then you will run into another problem as ServiceConnection doesn't have public parameterless constructor.
Resolution for this is to instruct DI container how to create ServiceConnection instance.
..
builder.Services.AddScoped<IConnectRepo, ConnectRepo>();
builder.Services.AddScoped<ServiceConnection>(sp => ServiceConnection.Create("some service URI"));
..
Be aware that you might need to use different service lifetime to avoid performance issues.
ServiceConnection documentation
IServiceCollection extension methods documentation
Using .NET Core 3.1 and Razor Pages.
I have two ways of authentication one for Windows and another for Azure using DistributedSqlServerCache, I trigger them depending on the environment:
For debug mode I use Windows authentication, and for release/prod I use Azure Active Directory.
Then I use Graph QL for calling getting user groups,
using Microsoft.Graph;
using Microsoft.Extensions.Caching.Distributed;
[Authorize]
[AuthorizeForScopes(ScopeKeySection = "DownstreamApi:Scopes")]
public class IndexModel : PageModel
{
private readonly GraphServiceClient _graphicServiceClient;
private IDistributedCache _cache;
public IndexModel(GraphServiceClient graphicServiceClient, IDistributedCache cache)
{
_graphicServiceClient = graphicServiceClient;
_cache = cache;
}
public async Task OnGet()
{
if (User.Identity.IsAuthenticated)
{
try
{
// use graph service here
}
}
}
Startup:
#if DEBUG
ConfigureWindowsAuthentication(services);
#else
ConfigureADAuthentication(services);
#endif
and somewhere configuring the services
_ = services.AddScoped<IGraphService, GraphService>();
This works on Azure Active Directory, but when I switch on Windows authentication I get the following exception:
}"2022-10-05 21:00:49.487 +08:00 [Information] Starting host
}Exception thrown: 'System.AggregateException' in Microsoft.Extensions.DependencyInjection.dll
"2022-10-05 21:00:50.600 +08:00 [Fatal] Host terminated unexpectedly
System.AggregateException: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: WebInterface.Code.Services.IGraphService Lifetime: Scoped ImplementationType: WebInterface.Code.Services.GraphService': Unable to resolve service for type 'Microsoft.Graph.GraphServiceClient' while attempting to activate 'WebInterface.Code.Services.GraphService'.)
---> System.InvalidOperationException: Error while validating the service descriptor 'ServiceType: WebInterface.Code.Services.IGraphService Lifetime: Scoped ImplementationType: WebInterface.Code.Services.GraphService': Unable to resolve service for type 'Microsoft.Graph.GraphServiceClient' while attempting to activate 'WebInterface.Code.Services.GraphService'.
---> System.InvalidOperationException: Unable to resolve service for type 'Microsoft.Graph.GraphServiceClient' while attempting to activate 'WebInterface.Code.Services.GraphService'.
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(Type serviceType, Type implementationType, CallSiteChain callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound)
I tried using abstraction and call the GraphicServiceClient from another service which I also add on the IndexModel constructor.
It only works on windows authentication when I remove the GraphicServiceClient from the constructor, is there anyway I could make them both go to work without change any code? I don't want to make two index models to switch between two.
Issue encountered when I try to add the first Migration in the project:
An error occurred while accessing the Microsoft.Extensions.Hosting services. Continuing without the application service provider. Error: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Microsoft.AspNetCore.Identity.ISecurityStampValidator Lifetime: Scoped ImplementationType: Microsoft.AspNetCore.Identity.SecurityStampValidator1[API.Entities.AppUser]': Unable to resolve service for type 'Microsoft.AspNetCore.Authentication.ISystemClock' while attempting to activate 'Microsoft.AspNetCore.Identity.SecurityStampValidator1[API.Entities.AppUser]'.) (Error while validating the service descriptor 'ServiceType: Microsoft.AspNetCore.Identity.ITwoFactorSecurityStampValidator Lifetime: Scoped ImplementationType: Microsoft.AspNetCore.Identity.TwoFactorSecurityStampValidator1[API.Entities.AppUser]': Unable to resolve service for type 'Microsoft.AspNetCore.Authentication.ISystemClock' while attempting to activate 'Microsoft.AspNetCore.Identity.TwoFactorSecurityStampValidator1[API.Entities.AppUser]'.)
Unable to create an object of type 'DataContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
The class where is inherited IdentityDbContext:
public class DataContext : IdentityDbContext<AppUser, AppRole, int,
IdentityUserClaim<int>,AppUserRole, IdentityUserLogin<int>,
IdentityRoleClaim<int>, IdentityUserToken<int>>
{
public DataContext(DbContextOptions<DataContext> options) : base(options)
{
}
DbSet<CVUser> UserWithCV { get; set; }
//Fluent API - used to overwrite the EF Core conventions
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
Then I have AppUser, which inherits IdentityUser
Startup Class:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<DataContext>(options =>
{
options.UseSqlite(_config.GetConnectionString("DefaultConnection"));
});
services.AddControllers();
//Setting up the Identity API
services.AddIdentityCore<AppUser>
(options =>
options.Password.RequireNonAlphanumeric = false
)
.AddRoles<AppRole>()
.AddRoleManager<RoleManager<AppRole>>()
.AddRoleValidator<RoleValidator<AppRole>>()
.AddEntityFrameworkStores<DataContext>()
.AddSignInManager<SignInManager<AppUser>>(); // - here is the problem
}
.AddSignInManager<SignInManager<AppUser>>();
this line is causing my issue when trying to add a new migration to the project. Any idea why ?
My only solution is to remove all of the following: (I'm guessing that Identity will create them by default correctly)
(If I remove the AddSignInManager I can create the Migration)
.AddRoles<AppRole>()
.AddRoleManager<RoleManager<AppRole>>()
.AddRoleValidator<RoleValidator<AppRole>>()
.AddSignInManager<SignInManager<AppUser>>();
What do you think ? Thank you.
Seems that I was missing services.AddAuthentication().
Thank you for the help #MartinCostello
I'm trying to use IHttpClientFactory. I've read the article https://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-3.0
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpClient();
services.AddSingleton<INasaStream, NasaStream>();
services.AddSingleton<INasaProvider, NasaProvider>();
}
// another methods remove for clearance
NasaStream.cs
public class NasaStream : INasaStream
{
// some variables declaration
public NasaStream(IOptions<AppSettings> options, HttpClient _client, ILogger<NasaProvider> _logger)
{
settings = options.Value;
client = _client;
logger = _logger;
}
}
There is no error with compilation. But when I try to run my app, there is an error:
Unhandled exception. System.AggregateException: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType:
Mars.INasaStream Lifetime: Singleton ImplementationType: Mars.NasaStream': Unable to resolve service for type 'System.Net.Http.HttpClient' while attempting to activate 'Mars.NasaStream'.) (Error while validating the service descriptor 'ServiceType: Mars.INasaProvider Lifetime: Singleton ImplementationType:
Mars.NasaProvider': Unable to resolve service for type 'System.Net.Http.HttpClient' while attempting to activate 'Mars.NasaStream'.) (Error while validating the service descriptor 'ServiceType: Mars.SolDataQuery Lifetime: Singleton ImplementationType: Mars.SolDataQuery': Unable to resolve service for type 'System.Net.Http.HttpClient' while attempting to activate 'Mars.NasaStream'.)
Why do I do wrong?
Ok, that's was my mistake. I couldn't see errors and debug log because I switched them off. It didn't mean that my code not work.
Correct answer was done by #Nkosi
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpClient<INasaStream, NasaStream>();
...
}
I should use typed client, that's all