Auto resolve DI with Scrutor - c#

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?

Related

InvalidOperationException: Unable to resolve service for type "" while attempting to activate dotnet core 7

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.

Can't get AuthorizationMessageHandler in Blazor WebAssembly to work due to service lifetime issues

I cannot get an HttpClient with AuthorizationMessageHandler working.
I have a project set up using the Microsoft.AspNetCore.Components.WebAssembly.Authentication package, and wired up for OIDC. That's working fine. Now, I want to make an http call to an API in another domain, using the access token provided during the OIDC authentication.
Based on https://learn.microsoft.com/en-us/aspnet/core/blazor/security/webassembly/additional-scenarios?view=aspnetcore-5.0#typed-httpclient, this should be a simple task, but I'm having all sorts of problems with the service collection. Here's what I have to set up a typed HttpClient:
builder.Services.AddScoped<AuthorizationMessageHandler>();
builder.Services.AddHttpClient<IAuthorizationClient, AuthorizationClient>(client => client.BaseAddress = new Uri(authUrl))
.AddHttpMessageHandler(sp => sp.GetRequiredService<AuthorizationMessageHandler>().ConfigureHandler(new[] { authUrl }));
The issue here, for example, is that AuthorizationMessageHandler requires an IAccessTokenProvider in the constructor, which Blazor provides as a Scoped service. However, the HttpClientFactory is registered as a singleton service. When the HttpClientFactory tries to activate an instance of AuthorizationMessageHandler, it fails with the following error:
Cannot resolve scoped service 'Microsoft.AspNetCore.Components.WebAssembly.Authentication.AuthorizationMessageHandler' from root provider.
Registering AuthorizationMessageHandler as a Singleton, I get:
Cannot consume scoped service 'Microsoft.AspNetCore.Components.WebAssembly.Authentication.IAccessTokenProvider' from singleton 'Microsoft.AspNetCore.Components.WebAssembly.Authentication.AuthorizationMessageHandler'.
Registering AuthorizationMessageHandler as a Transient, I get:
Cannot resolve 'Microsoft.AspNetCore.Components.WebAssembly.Authentication.AuthorizationMessageHandler' from root provider because it requires scoped service 'Microsoft.AspNetCore.Components.WebAssembly.Authentication.IAccessTokenProvider'.
I'm out of ideas on how to get this to work. All the examples in the referenced link above don't appear to work.
I've tried this with both net5.0 and net6.0, with the same result.

What does AddEntityFrameworkStores exactly do in AddIdentity?

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.

ConnectorStore changes in Bot Builder SDK 3.5.5?

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))

URL WCF RestFul .net with spring

I need to call my service with the standard url restful:
http://localhost/users : getall user
http://localhost/user/1 : get user with id 1
But the standard URLs in WCF looks like:
http://localhost/Userservice.svc/getallusers
I would like to change this, but since I use the Spring.net framework in my service WCF, I must create my Custom ServiceHostFactory MyServiceHostFactory
Spring is used in my project to do the injection dependencies and thus nothing new object
I try to add a route in global.asax
RouteTable.Routes.Add(new ServiceRoute("Users", new MyServiceHostFactory(), typeof(UserService)));
But when i call my service http://localhost/users
, I receive the error: ServiceHost only supports class service types
I don't understand the problem and is it possible to resolve this problem ?
Thanks for your help

Categories