Azure Function startup's Configure not being called - c#

I'm trying to create non-static functions in my Azure Function projet in .NET 5 (VS 2022) and the Startup Configure method is not being called.
Here's my start up class
[assembly: FunctionsStartup(typeof(AuthenticationGateway.Functions.Startup))]
namespace AuthenticationGateway.Functions
{
class Startup : FunctionsStartup //public or not, still does not get called.
{
public override void Configure(IFunctionsHostBuilder builder)
{
//break point here never gets hit...
}
}
}
And here's the function in question:
namespace AuthenticationGateway.Functions
{
public class CreationConnection
{
private AuthenticationGatewayContext Context { get; set; }
public CreationConnection(AuthenticationGatewayContext context)
{
Context = context;
}
[Function("CreationConnection")]
public HttpResponseData Run([HttpTrigger(AuthorizationLevel.Function, "get")] HttpRequestData req,
FunctionContext executionContext)
{
var response = req.CreateResponse(HttpStatusCode.OK);
return response;
}
}
}
I've tried commenting all of the code in Configure just in case it was a problem with it, not working either. Also tried marking the startup class as public too, no go.
Here are the dependencies for the projet in question
They are not the default dependencies the projet has when creating an Azure Function projet but as I tried other solutions to fix the issue, it lead me to plug those in.
Here's what the console is saying when starting the project:
Azure Functions Core Tools Core Tools Version: 3.0.3904 Commit
hash: c345f7140a8f968c5dbc621f8a8374d8e3234206 (64-bit) Function
Runtime Version: 3.3.1.0
Anything I missed ?
EDIT: I have reverted to the following dependencies as the previous ones made it so no functions would be found in the project.
On this page here it says those following dependencies have to be installed:
Microsoft.Azure.Functions.Extensions
Microsoft.NET.Sdk.Functions package version 1.0.28 or later
Microsoft.Extensions.DependencyInjection (currently, only version 3.x and earlier supported)
I have done so, except the last one because it is incompatible with .NET 5 it seems. Also, the project is now unbuildable:
error MSB4062: The "GenerateFunctionMetadata" task could not be loaded from the assembly

I have tried to reproduce the same issue which you got by following the below steps:
Created the Azure Functions (Stack: .Net5-v3) in VS2022.
Before adding Microsoft.Net.Sdk.functions to the project, it was built successfully.
After adding Microsoft.Net.Sdk.functions to the project, it has run to the same issue MSB4062 error as below:
By referencing these SO Thread1 and Thread2, removing Microsoft.Net.Sdk.functions will solve the compile issue.

Related

dotnet datacontext not able to migrate [duplicate]

I face the following error when adding the migration of database in .net core
This is the error:
This is the code in Startup:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<ApplicationUser>().AddEntityFrameworkStores<ApplicationDbContext>();
services.AddControllers();
}
This is the ApplicationDbContext class:
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{ }
public DbSet<ApplicationUser> applicationUsers { get; set; }
}
This is the ApplicationUser:
public class ApplicationUser : IdentityUser
{
[Required]
[Column(TypeName = "nvarchar(150)")]
public string UserFName { get; set; }
[Required]
public string UserLName { get; set; }
}
I found the cause of this error could be multiple things in your code. For me at least, the best way was to add verbose in command.
With that will be able to understand what is the problem. the verbose will display all steps of the execution.
In visual studio use:
add-migration Added_something -verbose
For the CLI use:
dotnet ef migrations add Added_something --verbose
This error can also occur if multiple startup projects is selected. I set my webproject to startup project and that solved the issue for me.
My problem was solved by installing Microsoft.EntityFrameworkCore.Design nuget package.
this package is required for the Entity Framework Core Tools to work. Ensure your startup project is correct.then install the package.
at the end Build -> Clean Solution in your project and then try running your command again.
Help Link
add migration command cli:
dotnet ef migrations add InitDatabase --project YourDataAccessLibraryName -s YourWebProjectName -c YourDbContextClassName --verbose
update database command cli:
dotnet ef database update InitDatabase --project YourDataAccessLibraryName -s YourWebProjectName -c YourDbContextClassName --verbose
remove migration command cli:
dotnet ef migrations remove --project YourDataAccessLibraryName -s YourWebProjectName -c YourDbContextClassName --verbose
Entity Framework Core tools reference - .NET Core CLI
I also had same problem today when I was running the dotnet ef migrations add <MigrationName>
I had three project, MainApp (Web), C# Project with DBContext and C# Project for Models.
I was able to resolve it from CLI.
dotnet ef migrations add AddCategoryTableToDb -s MainApp -p ProjectHavingDbContext
I had the same error when I had two constructors of my DbContext. After rearranging constructors order to parameterless constructor being first in the class fixed it. e.g.
public ProgramDbContext() : base()
{
}
public ProgramDbContext(DbContextOptions<ProgramDbContext> options) : base(options)
{
}
It must be something with dynamic DbContext object invocation with Reflection playing here.
This error also can occur if you remove the static IHostBuilder CreateHostBuilder(string[] args) method from Program.cs for your .net core app. (This was my case)
Seems you are your inheritance is wrong.
public ApplicationDbContext : IdentityDbContext
should be
public ApplicationDbContext : IdentityDbContext<ApplicationUser>
or
public ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole>
if you also extend roles class.
when you want to create an context with an extended user class (instead of IdentityUser)
Try This one as of March 2021 - VS 16.9.2
I tried many of the above answers and none worked for me. My issue was that we had multiple startup projects, so that was step one. Just set a single startup project, so I set our Data project to be the startup. Still got the error. Then it hit me (thanks to the #AFetter's answer) the Data project does NOT have a connection string within it. So I set my startup project to one with an appSettings.json file that HAS a connection to the DB and then made sure the Package Manager Console's Default Project was set to the Data project and reran the command to create the migration and it worked!
If you come to this issue while using .Net 6 along with the new minimal hosting model, check that you're not calling builder.build() before calling the AddDbContext on builder.services.
using MyProject.Data;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorPages();
string relativePath = ".";
string databasePath = Path.Combine(relativePath, "MyDb.sqlite");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlite($"Data Source={databasePath}") //connection string
);
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/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.UseAuthorization();
app.MapRazorPages();
app.Run();
I found I was missing:
Microsoft.EntityFrameworkCore.Tool
Microsoft.EntityFrameworkCore.Design
I had multiple startup projects (different API's).
I was at a different level in the PM console.
Then I learned I had to close SQL management so I can run PM console commands.
I was facing the same issue while running the dot net ef migrations script command from the azure pipeline task. I did added "-project" argument. But still was failing.
Adding the "-startup-project" argument worked for me.
I guess even though we specify startup class in project , for ef tool to find one we have to explicitly mention them.
In my case, I was missing a property in appsettings.json that was showing as Warning instead of Error
This error message is sometimes not directly related to the db context model. Check other errors in your Startup class such as missing properties/ credentials in your appsettings.json/ appsettings.Development.json
run your migration with the --verbose option to see all errors and warnings
dotnet ef migrations add YourMigrationName --verbose
If you are using Docker-Compose project. You need to unload the Docker-Compose project and then clean and rebuild the solution and set the startup project.
It worked for me to create the migration in EFCore.
Read this article: https://learn.microsoft.com/en-gb/ef/core/cli/dbcontext-creation?tabs=dotnet-core-cli#from-a-design-time-factory
The tooling tries to create a design-time DB context instance using various methods. One of those methods is to look for an implementation of the IDesignTimeDbContextFactory.
Some of the EF Core Tools commands (for example, the Migrations
commands) require a derived DbContext instance to be created at design
time in order to gather details about the application's entity types
and how they map to a database schema. In most cases, it is desirable
that the DbContext thereby created is configured in a similar way to
how it would be configured at run time.
Here's how your DB context factory class might look like:
public class ApplicationDbContextFactory : IDesignTimeDbContextFactory<ApplicationDbContext> {
public BlazorContext CreateDbContext(string[] args) {
var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
optionsBuilder.UseSqlite("Filename=db.sqlite3");
return new ApplicationDbContext(optionsBuilder.Options);
}
}
I faced the same problem in .Net 6
Make sure that AddDBContext is above builder.Build
builder.Services.AddDbContext<DatabaseDBContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("sqlConnection"))
);
var app = builder.Build();
In the Program.cs file, do not write anything with builder.Services.... below
var app = builder.Build()
line otherwise it throughs an error.
Although OP faced the issue seemingly due incorrect usage of base classes provided by AspNet Identity, but usually we come across this error when an instance of ApplicationDbContext could not be created at design time. There are couple of solutions for this. One of them is to specify the ApplicationDbContext provider in ConfigureServices method in StartUp class:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options => {
options.UseSqlServer(Configuration.GetConnectionString("MyConnection"));
});
}
For other solutions, please have a look at this link: https://learn.microsoft.com/en-gb/ef/core/miscellaneous/configuring-dbcontext#onconfiguring
I was getting the same error....except the code was working fine just minutes before.
I was in the process of replacing some property attributes with Fluent API
I had three projects: WebApp, DataAccess Library and Model Library.
After trying a few unsuccessful stabs at messing with migrations...I ended up doing a Build->Clean Solution and doing a build on the WebApp.
Every thing was working again...and I could not recreate the error.
This error happened to me, but at the same time I also had a An error occurred while accessing the Microsoft.Extensions.Hosting services. Continuing without the application service provider. Error: Could not parse the JSON file.
Fixing my appsettings.json file resolved the issue.
I had the same error, just modify the program class. Net Core 3.0
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
To
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
In my case, this was due to me storing my data types and migrations in a separate "Data" project and accidentally having it set as a startup project rather than my actual startup project.
Getting the same error...
Here's how I got there: Created a new ASP.NET Core Web App
(Model-View-Controller) Target Framework was .NET Core 3.1
(LTS) Authentication Type: Individual Accounts
Once the project was created...I wanted to be able to modify the register/login process.(but these pages are part of the Razor Class Library)
So to get the pages in the project: I right click the project Add->New Scaffolded Item...
And picked Identity...
Next I needed to Add-Migration InitIdentity...and this is where the errors/trouble starts.
I tried reading and working through some of the other answers with no success.
I found a solution by:
Creating the project like (above)
But this time I decided NOT to Scaffold Identity.(yet)
I put a connection string in the application.config and ran the project.
I did this before Add-Migration.
I went in to register...A screen came up and said the migration hasnt run yet and had a button to run the migration. I press it and did a refresh and all was good.
Its at this point I went back to the project and did a Add->Scafolded Item...and now there is no error and I have the Auth screens to modify.
Thoroughly inspect your appsettings file and endure it is well formed. Lookout fro missing characters or unnecessary characters
In my case I was using a custom IdentityErrorDescriber :
services.AddIdentity<AppIdentityUser, AppIdentityRole>()
.AddErrorDescriber<MyIdentityErrorDescriber>() // comment this !
.AddEntityFrameworkStores<MyDbContext>()
.AddDefaultTokenProviders();
and in my MyIdentityErrorDescriber I was using resources to translate errors.
and when I comment out the .AddErrorDescriber<MyIdentityErrorDescriber>() line the migration worked without any errors. I think the problem is either with the IdentityErrorDescriber or Resources.
I had three projects, one with Api, second with Models and third with ApplicationDbContext. Api project was starting project. I've added Microsoft.EntityFrameworkCore.Design nuget package to Api project (it's the starting project) and problem solved.
I faced the same error and when I added this it worked fine:
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ConnStr")));
services.AddScoped<IuserRepositorhy, UserRepository>();
I had two Configurations for Connection Strings in the app settings file, both missing a comma to separate both. When I put the comma, the error was gone.
This might not be your issue, but this is what caused the error on my end. If your app loads an environment variable at build time, that variable should be declared in the terminal. In my case, my app loaded my GOOGLE_APPLICATION_CREDENTIALS from a json file. I needed to export that variable before running anything related to build.
In my case, I built my project and it worked. So try to do this easy step before anything else.
For future reference, a simple gotcha, has got me before.
Make sure you actually have a value inside of the connection string in your appsettings.json file.
I.e.
This will throw an error:
"ConnectionStrings": {
"ConnectionString": ""
},
This will not:
"ConnectionStrings": {
"ConnectionString": "Server=server;Database=db;User Id=user;Password=password!;"
},
In my case, this error ocurred when i copied a project from tutorial repository. I managed to solve it by updating the project packages through NuGet Package Manager.

'No job functions found' .Net Azure Function after migration from Microsoft.Azure.WebJobs.ServiceBus to Microsoft.Azure.WebJobs.Extensions.ServiceBus

I am migrating some legacy .Net code from an App Service into an Azure Function triggered by a Service Bus topic. This will run under .Net Framework 4.8 as an Azure function V1. I am running into the error "No job functions found. Try making your job classes and methods public" etc.
To test this, I created a brand new Azure function using the Visual Studio 2022 template, and it does not have this warning. However, looking at the NuGet packages, I can see that the template installs Microsoft.Azure.WebJobs.ServiceBus, which is deprecated.
I removed that package and installed the new Microsoft.Azure.WebJobs.Extensions.ServiceBus package that is recommended.
The only change to the code that I had to make was to remove the AccessRights attribute, since that's not supported any more.
Now, when I run the Azure Function, I get the "No job functions found" warning.
The warning suggests that I am supposed to call config.UseServiceBus() somewhere. I've seen from some questions on this where people do this in Program.cs in the Main function. However, this is a DLL library project, so there is no Program.cs or startup code.
I've looked for a Migration Guide and searched for similar problems, but everything I've found is for .Net 5, not Framework 4.8.
What is the correct way to initialize a .Net48 Azure Function built as a DLL? Should I convert this project to a Console Program instead, and initialize in Main()?
Edit:
This is the template-generated function that works before updating the library:
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.ServiceBus.Messaging;
namespace AFTest
{
public static class Function1
{
[FunctionName("Function1")]
public static void Run([ServiceBusTrigger("testtopic", "testsubscription", AccessRights.Listen, Connection = "ServiceBusConnectionString")]string mySbMsg, TraceWriter log)
{
log.Info($"C# ServiceBus topic trigger function processed message: {mySbMsg}");
}
}
}
Here's the slightly modified code (removing the Access attribute) that doesn't work:
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
namespace AFTest
{
public static class Function1
{
[FunctionName("Function1")]
public static void Run([ServiceBusTrigger("testtopic", "testsubscription", Connection = "ServiceBusConnectionString")]string mySbMsg, TraceWriter log)
{
log.Info($"C# ServiceBus topic trigger function processed message: {mySbMsg}");
}
}
}

Trouble with Azure Function v3 in C#

I have a set of Azure Functions, written in C#, and running on Azure Function v2 runtime (.NET Core 2.2), which work just fine.
Now I was going to create a new set of Azure Function and I want to use the v3 runtime (.NET Core 3.1). However, when "transferring" the code from my existing code base, I ran into this problem: I have a Startup.cs file that's setting up the Dependency Injection for the Azure Functions, and this is what it looked like in my Azure Function v2 project:
[assembly: FunctionsStartup(typeof(MyCorp.MyProject.Infrastructure.Startup))]
namespace MyCorp.MyProject.RisWebportalService.Infrastructure
{
public class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
builder.Services.AddHttpClient();
// more lines here, setting up DI
}
}
}
When I tried to use this in the Azure Function v3 project, I get an error on the builder.Services.AddHttpClient(); line - seems IFunctionsHostBuilder in v3 doesn't have this extension method anymore......
So what do I do instead? I cannot seem to find any really useful documentation on any breaking changes in Azure Function runtime between v2 and v3 - any pointers?
You should install the package Microsoft.Extensions.Http, version 3.1.3.
The test result after installing it:
I found the same issue here.

Unable to create an object of type 'ApplicationDbContext'. For the different patterns supported at design time

I face the following error when adding the migration of database in .net core
This is the error:
This is the code in Startup:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<ApplicationUser>().AddEntityFrameworkStores<ApplicationDbContext>();
services.AddControllers();
}
This is the ApplicationDbContext class:
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{ }
public DbSet<ApplicationUser> applicationUsers { get; set; }
}
This is the ApplicationUser:
public class ApplicationUser : IdentityUser
{
[Required]
[Column(TypeName = "nvarchar(150)")]
public string UserFName { get; set; }
[Required]
public string UserLName { get; set; }
}
I found the cause of this error could be multiple things in your code. For me at least, the best way was to add verbose in command.
With that will be able to understand what is the problem. the verbose will display all steps of the execution.
In visual studio use:
add-migration Added_something -verbose
For the CLI use:
dotnet ef migrations add Added_something --verbose
This error can also occur if multiple startup projects is selected. I set my webproject to startup project and that solved the issue for me.
My problem was solved by installing Microsoft.EntityFrameworkCore.Design nuget package.
this package is required for the Entity Framework Core Tools to work. Ensure your startup project is correct.then install the package.
at the end Build -> Clean Solution in your project and then try running your command again.
Help Link
add migration command cli:
dotnet ef migrations add InitDatabase --project YourDataAccessLibraryName -s YourWebProjectName -c YourDbContextClassName --verbose
update database command cli:
dotnet ef database update InitDatabase --project YourDataAccessLibraryName -s YourWebProjectName -c YourDbContextClassName --verbose
remove migration command cli:
dotnet ef migrations remove --project YourDataAccessLibraryName -s YourWebProjectName -c YourDbContextClassName --verbose
Entity Framework Core tools reference - .NET Core CLI
I also had same problem today when I was running the dotnet ef migrations add <MigrationName>
I had three project, MainApp (Web), C# Project with DBContext and C# Project for Models.
I was able to resolve it from CLI.
dotnet ef migrations add AddCategoryTableToDb -s MainApp -p ProjectHavingDbContext
I had the same error when I had two constructors of my DbContext. After rearranging constructors order to parameterless constructor being first in the class fixed it. e.g.
public ProgramDbContext() : base()
{
}
public ProgramDbContext(DbContextOptions<ProgramDbContext> options) : base(options)
{
}
It must be something with dynamic DbContext object invocation with Reflection playing here.
This error also can occur if you remove the static IHostBuilder CreateHostBuilder(string[] args) method from Program.cs for your .net core app. (This was my case)
Seems you are your inheritance is wrong.
public ApplicationDbContext : IdentityDbContext
should be
public ApplicationDbContext : IdentityDbContext<ApplicationUser>
or
public ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole>
if you also extend roles class.
when you want to create an context with an extended user class (instead of IdentityUser)
Try This one as of March 2021 - VS 16.9.2
I tried many of the above answers and none worked for me. My issue was that we had multiple startup projects, so that was step one. Just set a single startup project, so I set our Data project to be the startup. Still got the error. Then it hit me (thanks to the #AFetter's answer) the Data project does NOT have a connection string within it. So I set my startup project to one with an appSettings.json file that HAS a connection to the DB and then made sure the Package Manager Console's Default Project was set to the Data project and reran the command to create the migration and it worked!
If you come to this issue while using .Net 6 along with the new minimal hosting model, check that you're not calling builder.build() before calling the AddDbContext on builder.services.
using MyProject.Data;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorPages();
string relativePath = ".";
string databasePath = Path.Combine(relativePath, "MyDb.sqlite");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlite($"Data Source={databasePath}") //connection string
);
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/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.UseAuthorization();
app.MapRazorPages();
app.Run();
I found I was missing:
Microsoft.EntityFrameworkCore.Tool
Microsoft.EntityFrameworkCore.Design
I had multiple startup projects (different API's).
I was at a different level in the PM console.
Then I learned I had to close SQL management so I can run PM console commands.
I was facing the same issue while running the dot net ef migrations script command from the azure pipeline task. I did added "-project" argument. But still was failing.
Adding the "-startup-project" argument worked for me.
I guess even though we specify startup class in project , for ef tool to find one we have to explicitly mention them.
In my case, I was missing a property in appsettings.json that was showing as Warning instead of Error
This error message is sometimes not directly related to the db context model. Check other errors in your Startup class such as missing properties/ credentials in your appsettings.json/ appsettings.Development.json
run your migration with the --verbose option to see all errors and warnings
dotnet ef migrations add YourMigrationName --verbose
If you are using Docker-Compose project. You need to unload the Docker-Compose project and then clean and rebuild the solution and set the startup project.
It worked for me to create the migration in EFCore.
Read this article: https://learn.microsoft.com/en-gb/ef/core/cli/dbcontext-creation?tabs=dotnet-core-cli#from-a-design-time-factory
The tooling tries to create a design-time DB context instance using various methods. One of those methods is to look for an implementation of the IDesignTimeDbContextFactory.
Some of the EF Core Tools commands (for example, the Migrations
commands) require a derived DbContext instance to be created at design
time in order to gather details about the application's entity types
and how they map to a database schema. In most cases, it is desirable
that the DbContext thereby created is configured in a similar way to
how it would be configured at run time.
Here's how your DB context factory class might look like:
public class ApplicationDbContextFactory : IDesignTimeDbContextFactory<ApplicationDbContext> {
public BlazorContext CreateDbContext(string[] args) {
var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
optionsBuilder.UseSqlite("Filename=db.sqlite3");
return new ApplicationDbContext(optionsBuilder.Options);
}
}
I faced the same problem in .Net 6
Make sure that AddDBContext is above builder.Build
builder.Services.AddDbContext<DatabaseDBContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("sqlConnection"))
);
var app = builder.Build();
In the Program.cs file, do not write anything with builder.Services.... below
var app = builder.Build()
line otherwise it throughs an error.
Although OP faced the issue seemingly due incorrect usage of base classes provided by AspNet Identity, but usually we come across this error when an instance of ApplicationDbContext could not be created at design time. There are couple of solutions for this. One of them is to specify the ApplicationDbContext provider in ConfigureServices method in StartUp class:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options => {
options.UseSqlServer(Configuration.GetConnectionString("MyConnection"));
});
}
For other solutions, please have a look at this link: https://learn.microsoft.com/en-gb/ef/core/miscellaneous/configuring-dbcontext#onconfiguring
I was getting the same error....except the code was working fine just minutes before.
I was in the process of replacing some property attributes with Fluent API
I had three projects: WebApp, DataAccess Library and Model Library.
After trying a few unsuccessful stabs at messing with migrations...I ended up doing a Build->Clean Solution and doing a build on the WebApp.
Every thing was working again...and I could not recreate the error.
This error happened to me, but at the same time I also had a An error occurred while accessing the Microsoft.Extensions.Hosting services. Continuing without the application service provider. Error: Could not parse the JSON file.
Fixing my appsettings.json file resolved the issue.
I had the same error, just modify the program class. Net Core 3.0
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
To
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
In my case, this was due to me storing my data types and migrations in a separate "Data" project and accidentally having it set as a startup project rather than my actual startup project.
Getting the same error...
Here's how I got there: Created a new ASP.NET Core Web App
(Model-View-Controller) Target Framework was .NET Core 3.1
(LTS) Authentication Type: Individual Accounts
Once the project was created...I wanted to be able to modify the register/login process.(but these pages are part of the Razor Class Library)
So to get the pages in the project: I right click the project Add->New Scaffolded Item...
And picked Identity...
Next I needed to Add-Migration InitIdentity...and this is where the errors/trouble starts.
I tried reading and working through some of the other answers with no success.
I found a solution by:
Creating the project like (above)
But this time I decided NOT to Scaffold Identity.(yet)
I put a connection string in the application.config and ran the project.
I did this before Add-Migration.
I went in to register...A screen came up and said the migration hasnt run yet and had a button to run the migration. I press it and did a refresh and all was good.
Its at this point I went back to the project and did a Add->Scafolded Item...and now there is no error and I have the Auth screens to modify.
Thoroughly inspect your appsettings file and endure it is well formed. Lookout fro missing characters or unnecessary characters
In my case I was using a custom IdentityErrorDescriber :
services.AddIdentity<AppIdentityUser, AppIdentityRole>()
.AddErrorDescriber<MyIdentityErrorDescriber>() // comment this !
.AddEntityFrameworkStores<MyDbContext>()
.AddDefaultTokenProviders();
and in my MyIdentityErrorDescriber I was using resources to translate errors.
and when I comment out the .AddErrorDescriber<MyIdentityErrorDescriber>() line the migration worked without any errors. I think the problem is either with the IdentityErrorDescriber or Resources.
I had three projects, one with Api, second with Models and third with ApplicationDbContext. Api project was starting project. I've added Microsoft.EntityFrameworkCore.Design nuget package to Api project (it's the starting project) and problem solved.
I faced the same error and when I added this it worked fine:
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ConnStr")));
services.AddScoped<IuserRepositorhy, UserRepository>();
I had two Configurations for Connection Strings in the app settings file, both missing a comma to separate both. When I put the comma, the error was gone.
This might not be your issue, but this is what caused the error on my end. If your app loads an environment variable at build time, that variable should be declared in the terminal. In my case, my app loaded my GOOGLE_APPLICATION_CREDENTIALS from a json file. I needed to export that variable before running anything related to build.
In my case, I built my project and it worked. So try to do this easy step before anything else.
For future reference, a simple gotcha, has got me before.
Make sure you actually have a value inside of the connection string in your appsettings.json file.
I.e.
This will throw an error:
"ConnectionStrings": {
"ConnectionString": ""
},
This will not:
"ConnectionStrings": {
"ConnectionString": "Server=server;Database=db;User Id=user;Password=password!;"
},
In my case, this error ocurred when i copied a project from tutorial repository. I managed to solve it by updating the project packages through NuGet Package Manager.

.NET Nancy 2 bootstrapper not firing

We have a Nancy Boostrapper class like so (Structure Map):
public class NancyBootstrapper : StructureMapNancyBootstrapper
{
protected override void ConfigureApplicationContainer(IContainer existingContainer)
{
existingContainer.Configure(ConfigureContainer);
}
}
When we run our application, this bootstrapper is found and the code hits ConfigureApplicationContainer(), all works well.
We then upgrade all Nancy packages from 1.4.1 to Nancy 2.
Upon running the application, this bootstrapper code is no longer hit.
We have isolated the issue specifically to the "Nancy.Hosting.Aspnet" package. When all Nancy packages are 2.0, this code is no longer hit. But as soon as we downgrade Nancy.Hosting.Aspnet to 1.4.1, it is successfully hit once again.
We're using the Nancy 2 "ClintEastwood" pre-release.
Has something in Nancy changed so that we can no longer use StructureMap bootstrappers?

Categories

Resources