I recently needed to Generate Email Confirmation Token for my .net core 5 app, and while researching I found out I need to register "AddIdentity" at startup.
services.AddIdentity<AuthenticatedUser, IdentityRole>(options =>
{
options.User.RequireUniqueEmail = false;
}).
AddEntityFrameworkStores<SchoolDataContext>().
AddDefaultTokenProviders();
If I remove 'AddEntityFrameworkStores' piece, then application builds and starts but crashes at runtime with similar errors like in following:
Error:
System.AggregateException: 'Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Microsoft.AspNetCore.Identity.IUserClaimsPrincipalFactory1[WebApp1.Areas.Identity.Data.ApplicationUser] Lifetime: Scoped ImplementationType: WebApp1.Areas.Identity.Data.AdditionalUserClaimsPrincipalFactory': Unable to resolve service for type 'Microsoft.AspNetCore.Identity.UserManager1[WebApp1.Areas.Identity.Data.ApplicationUser]' while attempting to activate 'WebApp1.Areas.Identity.Data.AdditionalUserClaimsPrincipalFactory'.)'
My question is why we even need to register "AddEntityFrameworkStores", I could not found a good documentation or source code implementation of it. Can't we just avoid to use it, or any idea why we need it at first place?
Here's the source code.
Basically it adds default Stores: UserStore and RoleStore. If you don't use it you have to provide Stores yourself with AddUserStore and AddRoleStore.
Related
I try add
using SciEn.Repo.Contracts;
using SciEn.Repo.IRepository;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddSingleton<ISubDepartmentRepository, SubDepartmentRepository>();
var app = builder.Build();
I got this error
'Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: SciEn.Repo.Contracts.ISubDepartmentRepository Lifetime: Scoped ImplementationType: SciEn.Repo.IRepository.SubDepartmentRepository': Unable to resolve service for type 'SciEn.Models.ScinceContext' while attempting to activate 'SciEn.Repo.IRepository.SubDepartmentRepository'.)'
I try remove
builder.Services.AddScoped<ISubDepartmentRepository, SubDepartmentRepository>();
but get error
InvalidOperationException: Unable to resolve service for type "" while attempting to activate
Unable to resolve service for type 'SciEn.Models.ScinceContext' while attempting to activate 'SciEn.Repo.IRepository.SubDepartmentRepository'.)
This error is telling you that when it tried to create the SubDepartmentRepository class it couldn't find the ScinceContext that needs to be injected into it's constructor.
You need to ensure you have registered the SciEn.Models.ScinceContext class.
Is this an Entity Framework DB Context? Make sure you've registered the DB Context...
builder.Services.AddDbContext<SciEn.models.ScinceContext>(...);
There are two things you need to care:
1.Create an instance of ScinceContext to pass into the SubDepartmentRepository.
2.Since DbContext is scoped by default, you need to create scope to access it.
Please check with your code something like below:
builder.Services.AddDbContext<ScinceContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("Connectionstring")));
builder.Services.AddScoped<ISubDepartmentRepository, SubDepartmentRepository>();
If you really need to use a dbContext inside a singleton, you can read this to know more.
I'm getting this warning while creating new MVC project using ASP.NET Core (both 3.1 version and 5.0 version):
dotnet quit unexpectedly
Because the warning description does show me where the problem comes from, so I don't know where to start.
This is my Startup.cs file:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseMigrationsEndPoint();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
}
}
Am I missing something?
There are multiple cases to get this warning. Some problem can be fixed inside the method ConfigureServices in the file Startup.cs.
If you are using Visual Studio, you can open Application Output tab (View -> Other Windows -> Application Output).
If you've got some message, such as:
Case 1:
Unhandled exception. System.InvalidOperationException: Unable to find
the required services. Please add all the required services by calling
'IServiceCollection.AddAuthorization' inside the call to
'ConfigureServices(...)' in the application startup code.
Fixed: Calling services.AddAuthorization(); method inside the ConfigureServices method.
Note: It's different from services.AddAuthentication(); (this service can be used when you want to enable some services like: Login with Facebook/Google/Twitter...).
Case 2:
Unhandled exception. System.InvalidOperationException: Unable to find
the required services. Please add all the required services by calling
'IServiceCollection.AddControllers' inside the call to
'ConfigureServices(...)' in the application startup code.
Fixed: Calling services.AddControllersWithViews(); or services.AddControllers(); service inside that method to solve the problem.
Case 3:
Unhandled exception. System.InvalidOperationException: Unable to find
the required services. Please add all the required services by calling
'IServiceCollection.AddRazorPages' inside the call to
'ConfigureServices(...)' in the application startup code.
This error ocurrs when you enable to use Razor Pages. To solve this problem, you need to add services.AddRazorPages(); service.
Case 4:
An unhandled exception has occurred while executing the request.
System.InvalidOperationException: No service for type
'Microsoft.AspNetCore.Identity.UserManager`1[Microsoft.AspNetCore.Identity.IdentityUser]'
has been registered.
You've got this error when missing to add identity service. This can be done by one of these ways:
services.AddDefaultIdentity<IdentityUser>(options =>
{
//options.Password.RequireDigit = false;
//options.Password.RequiredLength = 8;
//options.Password.RequireLowercase = false;
//options.Password.RequireNonAlphanumeric = false;
//options.Password.RequireUppercase = false;
}).AddEntityFrameworkStores<ApplicationDbContext>();
or
services.AddIdentity<IdentityUser, IdentityRole>(options =>
{
//options.Password.RequireDigit = false;
//options.Password.RequiredLength = 8;
//options.Password.RequireLowercase = false;
//options.Password.RequireNonAlphanumeric = false;
//options.Password.RequireUppercase = false;
}).AddEntityFrameworkStores<ApplicationDbContext>();
If you want to extend IdentityUser class to add more property like LastSignedIn:
public class User : IdentityUser
{
public DateTimeOffset LastSignedIn { get; set; }
}
you can replace IdentityUser with User when adding identity service:
services.AddIdentity<User, IdentityRole>(options => {})
.AddEntityFrameworkStores<ApplicationDbContext>();
Case 5:
Unhandled exception. System.AggregateException: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Microsoft.AspNetCore.Identity.IUserClaimsPrincipalFactory1[Microsoft.AspNetCore.Identity.IdentityUser] Lifetime: Scoped ImplementationType: Microsoft.AspNetCore.Identity.UserClaimsPrincipalFactory1[Microsoft.AspNetCore.Identity.IdentityUser]': Unable to resolve service for type 'X.Data.ApplicationDbContext' while attempting to activate 'Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserOnlyStore6[Microsoft.AspNetCore.Identity.IdentityUser,X.Data.ApplicationDbContext,System.String,Microsoft.AspNetCore.Identity.IdentityUserClaim1[System.String],Microsoft.AspNetCore.Identity.IdentityUserLogin1[System.String],Microsoft.AspNetCore.Identity.IdentityUserToken1[System.String]]'.) (Error while validating the service descriptor 'ServiceType: Microsoft.AspNetCore.Identity.UserManager1[Microsoft.AspNetCore.Identity.IdentityUser] Lifetime: Scoped ImplementationType: Microsoft.AspNetCore.Identity.UserManager1[Microsoft.AspNetCore.Identity.IdentityUser]': Unable to resolve service for type 'X.Data.ApplicationDbContext' while attempting to activate 'Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserOnlyStore6[Microsoft.AspNetCore.Identity.IdentityUser,X.Data.ApplicationDbContext,System.String,Microsoft.AspNetCore.Identity.IdentityUserClaim1[System.String],Microsoft.AspNetCore.Identity.IdentityUserLogin1[System.String],Microsoft.AspNetCore.Identity.IdentityUserToken1[System.String]]'.) (Error while validating the service descriptor 'ServiceType: Microsoft.AspNetCore.Identity.ISecurityStampValidator Lifetime: Scoped ImplementationType: Microsoft.AspNetCore.Identity.SecurityStampValidator1[Microsoft.AspNetCore.Identity.IdentityUser]': Unable to resolve service for type 'X.Data.ApplicationDbContext' while attempting to activate 'Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserOnlyStore6[Microsoft.AspNetCore.Identity.IdentityUser,X.Data.ApplicationDbContext,System.String,Microsoft.AspNetCore.Identity.IdentityUserClaim1[System.String],Microsoft.AspNetCore.Identity.IdentityUserLogin1[System.String],Microsoft.AspNetCore.Identity.IdentityUserToken1[System.String]]'.) (Error while validating the service descriptor 'ServiceType: Microsoft.AspNetCore.Identity.ITwoFactorSecurityStampValidator Lifetime: Scoped ImplementationType: Microsoft.AspNetCore.Identity.TwoFactorSecurityStampValidator1[Microsoft.AspNetCore.Identity.IdentityUser]': Unable to resolve service for type 'X.Data.ApplicationDbContext' while attempting to activate 'Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserOnlyStore6[Microsoft.AspNetCore.Identity.IdentityUser,X.Data.ApplicationDbContext,System.String,Microsoft.AspNetCore.Identity.IdentityUserClaim1[System.String],Microsoft.AspNetCore.Identity.IdentityUserLogin1[System.String],Microsoft.AspNetCore.Identity.IdentityUserToken1[System.String]]'.) (Error while validating the service descriptor 'ServiceType: Microsoft.AspNetCore.Identity.SignInManager1[Microsoft.AspNetCore.Identity.IdentityUser] Lifetime: Scoped ImplementationType: Microsoft.AspNetCore.Identity.SignInManager1[Microsoft.AspNetCore.Identity.IdentityUser]': Unable to resolve service for type 'X.Data.ApplicationDbContext' while attempting to activate 'Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserOnlyStore6[Microsoft.AspNetCore.Identity.IdentityUser,X.Data.ApplicationDbContext,System.String,Microsoft.AspNetCore.Identity.IdentityUserClaim1[System.String],Microsoft.AspNetCore.Identity.IdentityUserLogin1[System.String],Microsoft.AspNetCore.Identity.IdentityUserToken1[System.String]]'.) (Error while validating the service descriptor 'ServiceType: Microsoft.AspNetCore.Identity.IUserStore1[Microsoft.AspNetCore.Identity.IdentityUser] Lifetime: Scoped ImplementationType: Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserOnlyStore6[Microsoft.AspNetCore.Identity.IdentityUser,X.Data.ApplicationDbContext,System.String,Microsoft.AspNetCore.Identity.IdentityUserClaim1[System.String],Microsoft.AspNetCore.Identity.IdentityUserLogin1[System.String],Microsoft.AspNetCore.Identity.IdentityUserToken1[System.String]]': Unable to resolve service for type 'X.Data.ApplicationDbContext' while attempting to activate 'Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserOnlyStore6[Microsoft.AspNetCore.Identity.IdentityUser,X.Data.ApplicationDbContext,System.String,Microsoft.AspNetCore.Identity.IdentityUserClaim1[System.String],Microsoft.AspNetCore.Identity.IdentityUserLogin1[System.String],Microsoft.AspNetCore.Identity.IdentityUserToken`1[System.String]]'.)
This error ocurrs when you forget to enabling DbContext service:
// in this example, we use "Sqlite" to manage connection
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));
If you want to use SQL Server instead of Sqlite, you can add Microsoft.EntityFrameworkCore.SqlServer NPM package:
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
If you define ApplicationDbContext class in the class library project (Namespace: Your_main_project_namespace.Data), when you refer it to the main project, you need to call MigrationsAssembly method with the namspace name of the main project:
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
actions => actions.MigrationsAssembly("Your_main_project_namespace")));
Note: The current version (5.0.0) of this package is applied to net5.0, so if you're using netcoreapp3.1, you can use version 3.1.10 instead. Don't try to upgrade to the lastest, it will crash your project. Such as: removing/replacing some obsolete method/class/interface... (IWebHostEnvironment vs IHostingEnvironment...).
Case 6:
Value cannot be null. (Parameter 'connectionString')
This error may come from your connection string name in the file appsettings.json:
{
"ConnectionStrings": {
"MyConnection": "DataSource=app.db;Cache=Shared"
}
}
In this example, we name the connection string with the name MyConnection, so when we try to get:
Configuration.GetConnectionString("DefaultConnection")
the exception will be thrown because there is no property name DefaultConnection.
Case 7:
This problem may come from the way to append a large of data files to project via copy-paste method using Finder (on Mac) or Explorer (on Windows). The general case is: Coping to wwwroot folder:
When Visual Studio is opening and some files are copied to wwwroot folder (or somewhere else in the project) successful, the project will be saved automatically. There is no way to stop it.
And the remaining time will be calculated based on:
File count,
file size,
file type,
the target folder (wwwroot, node_modules...),
and your hardware (CPU, RAM, HDD or SSD).
So, be careful if you want to copy more than 5000 images or videos to wwwroot folder. If something goes wrong (I don't even know where the error comes from), you cannot run the project. In this case, I suggest:
Wait until your project completes saving/loading/restoring. DO NOT take any action to try to stop or prevent it.
Right click the project and choose Edit Project File to edit .csproj file. In this file, if you catch some implementation like this:
<ItemGroup>
<Content Include="wwwroot\">
<CopyToPublishDirectory>Always</CopyToPublishDirectory>
</Content>
</ItemGroup>
The tag <ItemGroup> which contains <Content> tag, and the <Content> tag mentions about wwwroot folder or some folder name that inherits from wwwroot folder. DELETE all of them (including the parent tag: <ItemGroup>), save the file and wait until the file is saved/all packages are restored.
Clean the project and buid/rebuild again.
More action: If the building/loading speed of your project becomes very slow, try to right click on the target folder (in this case: wwwroot) and choose Exclude From Project. Then waiting until Visual Studio completes the action, and right click the folder to choose Include From Project again. Waiting action is required (the time to exclude/include may the same).
I have app service ExperienceAppService that implements interface IExperienceAppService.
I try to use Scrutoк for auto registering
I have this code in Startup file
services.Scan(scan =>
scan.FromCallingAssembly()
.AddClasses()
.AsMatchingInterface());
It supposed to register interface . But I got this error
Unable to resolve service for type 'TooSeeWeb.Core.Interfaces.Experiences.IExperienceAppService' while attempting to activate 'TooSeeWeb.Controllers.ExperienceController'.
Where is my trouble?
I’m upgrading Bot Builder SDK for our bot from 3.5.0 to 3.5.5 due to LUIS endpoint being deprecated in few weeks and it seems like latest SDK version has a way to specify ‘LuisApiVersion’.
During upgrade, I’m getting following error while modifying the behavior to use LastWriteWins policy for CachingBotDataStoreConsistencyPolicy:
Exception thrown:
'Autofac.Core.Registration.ComponentNotRegisteredException' in autofac.dll
Additional information: The requested service 'Microsoft.Bot.Builder.Dialogs.Internals.ConnectorStore' has not been registered. To avoid this exception, either register a component to provide the service, check for service registration using IsRegistered(), or use the ResolveOptional() method to resolve an optional dependency.
builder.Register(c => new CachingBotDataStore(c.Resolve<ConnectorStore>(),
CachingBotDataStoreConsistencyPolicy.LastWriteWins)
.As<IBotDataStore<BotData>>()
.AsSelf()
.InstancePerLifetimeScope();
This code has worked for 3.5.0, but I’m not sure what’s the best way to handle the Autofac error that we are getting with 3.5.5. Any pointers or idea about this?
The registration of ConnectorStore has changed as you can see here.
To solve the issue you should change the c.Resolve<ConnectorStore>() in the your code to c.ResolveKeyed<IBotDataStore<BotData>>(typeof(ConnectorStore))
A new asp.net mvc project using owin, webapi, mvc and DI (SimpleInjector) runs fine if I remove the DI lib from the project. However, once introduced, the app blows up when registering the OWIN components for DI. The OWIN startup configuration is being hit and runs without error, but when it comes time to register the dependencies (listed below) I receive the following error:
An exception of type 'System.InvalidOperationException' occurred in Microsoft.Owin.Host.SystemWeb.dll but was not handled in user code
Additional information: No owin.Environment item was found in the context.
SimpleInjector Registration Code:
container.RegisterPerWebRequest<IUserStore<ApplicationUser>>(() => new UserStore<ApplicationUser>());
container.RegisterPerWebRequest<HttpContextBase>(() => new HttpContextWrapper(HttpContext.Current));
// app fails on call to line below...
container.RegisterPerWebRequest(() => container.GetInstance<HttpContextBase>().GetOwinContext());
container.RegisterPerWebRequest(() => container.GetInstance<IOwinContext>().Authentication);
container.RegisterPerWebRequest<DbContext, ApplicationDbContext>();
Update - Full Stack Trace
at
System.Web.HttpContextBaseExtensions.GetOwinContext(HttpContextBase
context) at
WebApplication1.App_Start.SimpleInjectorInitializer.<>c__DisplayClass6.b__2()
in
b:\temp\WebApplication1\WebApplication1\App_Start\SimpleInjectorInitializer.cs:line
41 at lambda_method(Closure ) at
SimpleInjector.Scope.CreateAndCacheInstance[TService,TImplementation](ScopedRegistration2
registration) at
SimpleInjector.Scope.GetInstance[TService,TImplementation](ScopedRegistration2
registration) at
SimpleInjector.Scope.GetInstance[TService,TImplementation](ScopedRegistration2
registration, Scope scope) at
SimpleInjector.Advanced.Internal.LazyScopedRegistration2.GetInstance(Scope
scope) at lambda_method(Closure ) at
SimpleInjector.InstanceProducer.GetInstance()
I think the exception is thrown when you call Verify(). Probably at that line, but only when the delegate is called.
Simple Injector allows making registrations in any order and will therefore not verify the existence and correctness of a registration’s dependencies. This verification is done the very first time an instance is requested, or can be triggered by calling .Verify() at the end of the registration process.
I suspect you're registrering the OwinContext only because you need it for getting the IAuthenticationManager.
The problem you face is that the OwinContext is only available when there is a HttpContext. This context is not available at the time the application is build in the composition root. What you need is a delegate which checks the stage of the application and returns a component that matches this stage. You could that by registering the IAuthenticationManager as:
container.RegisterPerWebRequest<IAuthenticationManager>(() =>
AdvancedExtensions.IsVerifying(container)
? new OwinContext(new Dictionary<string, object>()).Authentication
: HttpContext.Current.GetOwinContext().Authentication);
The delegate will return the Owin controlled IAuthenticationManager when the code runs at 'normal runtime stage' and there is a HttpContext.
But when making an explicit call the Verify() (which is highly advisable to do!) at the end of registration process there is no HttpContext. Therefore we will create a new OwinContext during verifying the container and return the Authentication component from this newly created OwinContext. But only if the container is indeed verifying!
A full and detailed description can be read here as already mentioned in the comments.
Although the question is different, the answer is the same as my answer here.
The problem is that you are injecting HttpContextWrapper into your application and attempting to use its members during application initialization, but at that point in the application lifecycle, HttpContext is not yet available. HttpContext contains runtime state, and it does not make sense to initialize an application within one specific user's context.
To get around this problem, you should use one or more Abstract Factories to access HttpContext at runtime (when it is available) rather than at application initialization, and inject the factories into your services with DI.
Using Ric .Net's answer might work, too, but it will throw an exception every time the application is initialized.
The answer of 'Ric .Net' has pointed me in right direction, but to allow changes to new SimpleInjector, have to change the code as below (as RegisterPerWebRequest is obselete):
container.Register<IAuthenticationManager>(() => AdvancedExtensions.IsVerifying(container)
? new OwinContext(new Dictionary<string, object>()).Authentication
: HttpContext.Current.GetOwinContext().Authentication, Lifestyle.Scoped);
Also, have to add below two registrations to the container, to allow 'container.Verify()' to work correctly:
container.Register<ApplicationUserManager>(Lifestyle.Scoped);
container.Register<ApplicationSignInManager>(Lifestyle.Scoped);