InvalidOperationException: Unable to resolve service for type 'Context.dbcontext' while attempting to activate 'Api.Controllers.ReportsController'.
enter image description here
In .net6:
Add this line to Program.cs:
builder.Services.AddDbContext<dbcontext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("connectionstring")));
In .net5 or others:
Add this line to Startup.cs:
services.AddDbContext<dbcontext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("connectionstring")));
For more details,you can refer to this document.
Related
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();
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.
I have 2 projects ones call Api which is a library for my DbContext and other call AdminPanel which is an Asp.NetCore project for my website.
in The Api Project my Dbcontext inherit IdentityDbContext<AppUser> and the
Appuser class is in the same project in model folder which inherited from IdentityUser class.
Now in my AdminPanel in Startup.cs i use
services.AddIdentity<ApplicationUser, IdentityRole>(config =>
{
config.User.RequireUniqueEmail = true;
config.Password.RequiredLength = 8;
})
.AddEntityFrameworkStores<MyDbContext>()
.AddDefaultTokenProviders();
services.AddScoped<IUserClaimsPrincipalFactory<ApplicationUser>, AppClaimsPrincipalFactory>();
services.AddScoped<SignInManager<ApplicationUser>, AuditableSignInManager<ApplicationUser>>();
which ApplicationUser is a class in AdminPanel now when i run AdminPanel project i'll get
An error occurred during the compilation of a resource required to
process this request. Please review the following specific error
details and modify your source code appropriately.
Generated Code
One or more compilation references are missing. Ensure that your project is referencing 'Microsoft.NET.Sdk.Web' and the
'PreserveCompilationContext' property is not set to false.
The type or namespace name 'ApplicationUser' could not be found (are you missing a using directive or an assembly reference?)
I don't know what should i do.
beforehand Sorry about my English. Thanks for your help.
I installed Swagger in my ASP.Net MVC Core project and it is documenting my API beautifully.
My co-worker asked me to install it in a full framework 4.6.1 project so I've done the following.
In Package Console Manager run:
Install-Package Swashbuckle
To get your Test Web API controller working:
1) Comment this out in the WebApi.config:
// config.SuppressDefaultHostAuthentication();
// config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
Now this URL:
http://localhost:33515/api/Test
brings back XML:
<ArrayOfstring xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<string>value1</string>
<string>value2</string>
</ArrayOfstring>
In Global.asax Register() I call:
SwaggerConfig.Register();
In AppStart.Swagger.Config Register() I put:
public class SwaggerConfig
{
public static void Register()
{
var thisAssembly = typeof(SwaggerConfig).Assembly;
GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
c.SingleApiVersion("v1.0", "HRSA CHAFS");
c.IncludeXmlComments(GetXmlCommentsPath());
})
.EnableSwaggerUi(c =>
{});
}
private static string GetXmlCommentsPath()
{
var path = String.Format(#"{0}bin\Services.XML", AppDomain.CurrentDomain.BaseDirectory);
return path;
}
}
Now I get this error:
"A route named 'swagger_docsswagger/docs/{apiVersion}' is already in the route collection. Route names must be unique."
I've been stuck on this for hours.
How do you get rid of this?
This can happen when you re-name your .NET assembly. A DLL with the previous assembly name will be present in your bin folder. This causes the swagger error.
Delete your bin folder and re-build your solution.
This resolves the swagger error.
Swagger config uses pre-application start hook, so you don't need to call SwaggerConfig.Register() explicitly. Otherwise Register method is called twice.
[assembly: PreApplicationStartMethod(typeof(SwaggerConfig), "Register")]
in my case i added another project as refrence and that other project has swagger too.
i remove that refrence and move needed code to new project.
I solved the problem by deleting the SwaggerConfig.cs file from the App_Start folder as I had already created it manually.
Take a look at this link, here also has more useful information:
A route named 'DefaultApi' is already in the route collection error
In my experience the error occurs when you add reference to another project and that project is a service and it occurs on the SwaggerConfig of the referenced project. Removing project reference usually solve the problem, if you need to share classes I suggest you to create a specific project as Class Library and add its reference to both your services
I am creating Asp.net core application and trying to connect to the database. I am getting an error at the following line of code in ConfigureServices method in the startup.cs file. The error that I am getting is the value cannot be null. It seems like it cant find the CustomerOrderEntities key in the web.config file. Not sure what the problem is
services.AddDbContext<CustomerOrderEntities>(options =>
options.UseSqlServer(Configuration.GetConnectionString("CustomerOrderEntities")));
Startup.cs
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddDbContext<CustomerOrderEntities>(options =>
options.UseSqlServer(Configuration.GetConnectionString("CustomerOrderEntities")));
AutoMapperConfiguration.Configure();
// Create the container builder.
var builder = new ContainerBuilder();
// Register dependencies, populate the services from
// the collection, and build the container. If you want
// to dispose of the container at the end of the app,
// be sure to keep a reference to it as a property or field.
builder.RegisterType<UnitOfWork>().As<IUnitOfWork>();
builder.RegisterType<DbFactory>().As<IDbFactory>();
builder.RegisterType<CustomerRepository>().As<ICustomerRepository>();
builder.RegisterType<ProductRepository>().As<IProductRepository>();
builder.RegisterType<OrderRepository>().As<IOrderRepository>();
builder.Populate(services);
this.ApplicationContainer = builder.Build();
// Create the IServiceProvider based on the container.
return new AutofacServiceProvider(this.ApplicationContainer);
}
Web.Config
<connectionStrings>
<add name="CustomerOrderEntities" connectionString="metadata=res://*/EF.CustomerOrderContext.csdl|res://*/EF.CustomerOrderContext.ssdl|res://*/EF.CustomerOrderContext.msl;provider=System.Data.SqlClient;provider connection string="data source=test-PC\MSSQLSERVER2014;initial catalog=CodeFirstTest;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
Connection string in ASP.NET Core is defined in appsettings.json, for example:
"ConnectionStrings": {
"CustomerOrderEntities": "Server=(localdb)\\mssqllocaldb;Database=aspnet-a3e892a5-6a9c-4090-bc79-fe8c79e1eb26;Trusted_Connection=True;MultipleActiveResultSets=true"
},
In your case name of connecting string is CustomerOrderEntities, you get null, probably it's not there, check you appsettings.json.
Your connectionstring in Appsettings.json is definitely missing. You cannot set connection string in web.config in Asp.net core whether you are targeting full .net framework or .net core. Alternative you type the connection string value in services.AddDbContext(options =>
options.UseSqlServer("Your Connectionstring"));
for more information check here;
https://learn.microsoft.com/en-us/ef/core/