ASP.NET Core 3.1 services.AddSession(); causes crash - asp.net-core

When I add
services.AddSession();
to my startup in my core 3.1 I get
Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Microsoft.AspNetCore.Session.ISessionStore Lifetime: Transient ImplementationType: Microsoft.AspNetCore.Session.DistributedSessionStore': Unable to resolve service for type 'Microsoft.Extensions.Caching.Distributed.IDistributedCache' while attempting to activate 'Microsoft.AspNetCore.Session.DistributedSessionStore'.) on stack: at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(IEnumerable`1 serviceDescriptors, ServiceProviderOptions options)
at Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(IServiceCollection services, ServiceProviderOptions options)
at Microsoft.Extensions.DependencyInjection.DefaultServiceProviderFactory.CreateServiceProvider(IServiceCollection containerBuilder)
at Microsoft.Extensions.Hosting.Internal.ServiceFactoryAdapter`1.CreateServiceProvider(Object containerBuilder)
at Microsoft.Extensions.Hosting.HostBuilder.CreateServiceProvider()
at Microsoft.Extensions.Hosting.HostBuilder.Build()
At no time did I as for DistributedSessionStore, I just added the line AddSession and did not add any nuget packages, where is it getting this data from?
When I go to the definition on services.AddSession() it takes me to
Assembly Microsoft.AspNetCore.Session
Quite surprised as to what this error is all about.

I think that the only way to safely test for session is to use some code like this:
if(HttpContext.Features.Get<ISessionFeature>()?.Session != null && HttpContext.Session.IsAvailable)
{
...
}

Related

dependency injection of interface in Quartz.NET for Execute job

i use asp.net core and Quartz.NET
in need inject interface like this
to execute job
public class RemoveSmsSendQueueJob : IJob
{
private readonly ISmsQueueService _smsQueueService;
public RemoveSmsSendQueueJob(ISmsQueueService smsQueueService)
{
_smsQueueService = smsQueueService;
}
public Task Execute(IJobExecutionContext context)
{
_smsQueueService.UpdateQueue();
return Task.CompletedTask;
}
}
but get this error
System.InvalidOperationException: 'No service for type 'Khanoumi.eShop.Notification.Service.RemoveSmsSendQueueJob' has been registered.'
i try add
services.AddSingleton<ISmsQueueService, SmsQueueService>();
or
services.AddScoped<ISmsQueueService, SmsQueueService>();
or
services.AddTransient<ISmsQueueService, SmsQueueService>();
in startup
but any time have other error
how can i fix this?
full error is :
Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Khanoumi.eShop.Notification.Service.RemoveSmsSendQueueJob Lifetime: Singleton ImplementationType: Khanoumi.eShop.Notification.Service.RemoveSmsSendQueueJob': Unable to resolve service for type 'Khanoumi.eShop.Notification.Service.ISmsQueueService' while attempting to activate 'Khanoumi.eShop.Notification.Service.RemoveSmsSendQueueJob'.)'
This error is telling you that your job has not been added to the DI pipeline. Here is a quick way to add it in Startup.cs:
services.AddTransient<RemoveSmsSendQueueJob>();
Then you can inject later with no issue.
You should try the new built-in integration available in 3.1. Here is the documentation how to get started.

Unable to resolve service for type 'System.Object' while attempting to activate 'MediatR.ServiceFactory'

I have an Asp.net Core 2.2 app that I'm trying to upgrade to 3.0. I'm using Mediatr and now I got this error after upgrading to 3.0
Error while validating the service descriptor 'ServiceType: System.ICloneable Lifetime: Transient ImplementationType: MediatR.ServiceFactory': Unable to resolve service for type 'System.Object' while attempting to activate 'MediatR.ServiceFactory'.
Here is my code in the Startup.cs
services.AddMediatR(typeof(BlogPost));
and I'm using Scrutor to scan IMediator
services.Scan(scan => scan
.FromAssembliesOf(typeof(ISettingService), typeof(IMediator), typeof(BlogPost), typeof(IHomeHelper))
.AddClasses()
.UsingRegistrationStrategy(RegistrationStrategy.Skip)
.AsImplementedInterfaces()
.WithScopedLifetime());
The above code works in 2.2, but now I cannot get the program to even launch due to the error. Could someone shed some light on what is going wrong please?
Disable validate scope.
// Program.cs
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseDefaultServiceProvider(options => options.ValidateScopes = false) // <<<<<<<<<<<
.Build();

Xamarin.Forms Add Connected Service on WCF only generated async method

I just begun to do Xamarin.Forms with .Net Standard 2.0 (PCL) project. I'm trying to consume my WCF web service but never got it successfully done.
I have created a simple WCF as below
[ServiceContract]
public interface IWcfConnection
{
[OperationContract]
string GetHelloWorld();
}
the implementation as below
public class WcfConnection : IWcfConnection
{
public string GetHelloWorld()
{
return "Hello World";
}
}
It's a very simple WCF, when I go to my Xamarin.Forms and right click on the "Connected Service", there is no "Add Web Service", but only "Add Connected Service", so I selected that as below
Then select "Microsoft WCF Web Service Service Provider"
Select the option as below (I untick everything because if I add more than 1 service, it will crash)
When I look into the reference.cs created, there is only async method created.
public System.Threading.Tasks.Task<string> GetHelloWorldAsync()
{
return base.Channel.GetHelloWorldAsync();
}
1) May I know why only async is created? Is it for .net standard and core, only async services will be created? As I read somewhere.
2) If so, how do I consume the web service?
In my xaml.cs file, I did the following,
WcfConnectionService.WcfConnectionClient client = new WcfConnectionService.WcfConnectionClient(new WcfConnectionService.WcfConnectionClient.EndpointConfiguration());
string abc = client.GetHelloWorldAsync().GetAwaiter().GetResult();
But I'm getting error and unable to work accordingly. Anybody got any idea?
Unhandled Exception:
System.ServiceModel.FaultException`1[[System.ServiceModel.ExceptionDetail, System.ServiceModel, Version=2.0.5.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]: Error in deserializing body of request message for operation 'GetHelloWorld'. OperationFormatter encountered an invalid Message body. Expected to find node type 'Element' with name 'GetHelloWorld' and namespace 'http://tempuri.org/'. Found node type 'Element' with name 'GetHelloWorldAsync' and namespace 'http://tempuri.org/'
At the moment Xamarin apps aren't compatible with the Task-based asynchronous WCF proxy methods that the WCF Web Service Reference connected service provider generates for .NET Standard projects (bugzilla.xamarin.com Bug 51959).
Generate an older compatible style of WCF proxy methods via checked "Generate Synchronous Operations" checkbox on Configure WCF Web Service Reference screen:
Consume the web service:
KimlikServiceReference.KPSPublicSoapClient soapClient = new KimlikServiceReference.KPSPublicSoapClient(KimlikServiceReference.KPSPublicSoapClient.EndpointConfiguration.KPSPublicSoap);
//KimlikServiceReference.TCKimlikNoDogrulaResponse response = soapClient.TCKimlikNoDogrulaAsync(TCKimlikNo, Ad, Soyad, DogumYili).Result;
bool result = soapClient.TCKimlikNoDogrula(TCKimlikNo, Ad, Soyad, DogumYili);

HTTP Error 500.30 - ANCM In-Process Start Failure error in ASP.NET Core 2.2

I am configuring this application
Confirming the account and recovering passwords in ASP.NET Core
but I have an error:
HTTP Error 500.30 - ANCM In-Process Start Failure Common causes of
this issue: The application failed to start The application started
but then stopped The application started but threw an exception during
startup Troubleshooting steps: Check the system event log for error
messages Enable logging the application process' stdout messages
Attach to debugger to the application process and inspect http 500
when replacing this code in IdentityHostingStartup
Below is my configuration:
[assembly: HostingStartup(typeof(Misioneros.Stella.Maris.Web.Areas.Identity.IdentityHostingStartup))]
namespace Misioneros.Stella.Maris.Web.Areas.Identity
{
public class IdentityHostingStartup : IHostingStartup
{
public void Configure(IWebHostBuilder builder)
{
builder.ConfigureServices((context, services) => {
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
context.Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<IdentityUser>(config =>
{
config.SignIn.RequireConfirmedEmail = true;
})
.AddEntityFrameworkStores<ApplicationDbContext>();
});
}
}
}
Any idea what is the problem?
I've had the 500.30 error due to the duplicate identity problem cited by TanvirArjel, but I also just encountered the error when my appsettings.json file had some bad JSON in it. Not sure if that would only occur if you're actually trying to use configuration values in Startup.
I got the reason. May be you are registering Identity twice in your application as follows:
One in ConfigureServices method of the startup class:
services.AddDefaultIdentity<IdentityUser>()
.AddDefaultUI(UIFramework.Bootstrap4)
.AddEntityFrameworkStores<ApplicationDbContext>();
And other in the IdentityHostingStartup :
services.AddDefaultIdentity<IdentityUser>(config =>
{
config.SignIn.RequireConfirmedEmail = true;
}).AddEntityFrameworkStores<ApplicationDbContext>();
Register Identity just in one place i.e either in ConfigureServices method or in IdentityHostingStartup.
Hope this will help you.
I had this error come up. It turned out the root was because the app I was working with used Azure Key Vault, and I was using the wrong identity to authenticate with Azure.
I had to go to Tools > Options > Azure Service Authentication and change the identity used for Azure service authentication.
If you have no idea what the reason of that behavior, you can enable logging in the web.config file
<aspNetCore processPath="dotnet" arguments=".\WMC.Web.dll" stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout" hostingModel="inprocess" />
and then in the logs folder you will find the detailed description of your exception
What solved this exact error for me (in .NET Core 2.2) on the production IIS server was disabling 32-bit application support in my application pool. Everything worked fine on my local Win10 IIS Express setup.
I published my application from Visual Studio 2019 (Publish > Settings tab) as "Deployment Mode: Framework dependent" and "Target Runtime: win-x64." I'm not sure if the former option matters or not.
To remedy the error on the IIS Server, I needed to go into "Advanced Settings" on my application pool and set "Enable 32-bit Applications" to "False." You can also do this at the global level if it makes sense to. You'll find the global "Advanced Settings" on the right in the "Actions" pane.
I had the same issue when I had a web application and a web api site (from the same solution) using the same application pool. I resolved the issue when I created a new application pool for the web api so that it was no longer sharing the app pool with the web application.
I got 500.30 when updating openiddict 2.0.0-rc2-final to openiddict 2.0.0
TanvirArjel's answer, pointed me to remove .AddOAuthValidation(); from StartUp.cs
public void ConfigureServices(IServiceCollection services)
{
// updated openiddict
services.AddOpenIddict()
.AddCore(options => { /*removed for brevity*/ })
.AddServer(options => { /*removed for brevity*/ })
.AddValidation();
services.AddAuthentication(options => { /*removed for brevity*/ })
.AddCookie()
.AddOAuthValidation(); // this line
}
Add try catch block in program.cs may help to solve the issue
public static void Main(string[] args)
{
try {
CreateWebHostBuilder(args).Build().Run();
}
catch (Exception exception)
{
Console.WriteLine(exception.Message);
}
}
I received this problem after visual studio updating at version 16.4.1, I resolved it with changing a package reference in cs.proj:
from
PackageReference Include="Microsoft.AspNetCore" Version="2.2.0"
to PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.2.0"
I just try to enable all the feature relate to ASP in the Windows features > Internet Information Services > World Wide Web Services > Application Development Features.

Adding services in asp.net core project

Is there a way to map all my repository objects to its interfaces in a single line. I donĀ“t want to repeat my self in declarations like these:
services.AddScoped<Repository.Interfaces.IModeloRepository, Repository.ModeloRepository>();
services.AddScoped<Repository.Interfaces.IMunicipioRepository, Repository.MunicipioRepository>();
services.AddScoped<Repository.Interfaces.IPeriodoRepository, Repository.PeriodoRepository>();
services.AddScoped<Repository.Interfaces.IPlanRepository, Repository.PlanRepository>();
Here is a declaration of one of these repositories:
public interface IChatRepository : IRepository<Models.Chat>
I already tried something like this:
services.AddScoped(typeof(Repository.Common.IRepository<>), typeof(Repository.Common.BaseRepository<>));
But gets the following error:
Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware[0]
An unhandled exception has occurred: Unable to resolve service for type 'SqlExpress.Repository.Interfaces.IChatRepository' while attempting to activate 'SqlExpress.Helpers.LessonTagHelper'.
System.InvalidOperationException: Unable to resolve service for type 'SqlExpress.Repository.Interfaces.IChatRepository' while attempting to activate '
SqlExpress.Helpers.LessonTagHelper'.
at Microsoft.Extensions.Internal.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)
at lambda_method(Closure , IServiceProvider , Object[] )
Unfortunately, the built in DI container in ASP.NET Core is relatively simplistic. If you would like to use more advanced features like these, then you will need to use a different container.
The example below uses StructureMap as that's what I'm familiar with, but it is probably also possible with Autofac, Ninject etc.
Add the StructureMap library to project.json
"StructureMap.Dnx": "0.5.1-rc2-final"
Configure the DI container to use StructureMap, with naming conventions:
public IServiceProvider ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc().AddControllersAsServices();
// other service configuration
// Create a new StructureMap container
var container = new Container();
container.Configure(config =>
{
//add all the services that are already configured
config.Populate(services);
config.Scan(_ =>
{
_.WithDefaultConventions();
_.AssemblyContainingType<Startup>();
_.ConnectImplementationsToTypesClosing(typeof(IRepository<>));
});
});
//set ASP.NET Core to use the StructureMap container to build types
return container.GetInstance<IServiceProvider>();
}
It is worth checking our the documentation to see exactly how this works, but the default convention is to automatically register interface types such as IMyInterestingType with their implementation called MyInterestingType.
By using ConnectImplementationsToTypesClosing, each IRepository<> should also be registered to it's implementation.