Unable to consume MSBuild properties in service resolving source generator - c#

I use Injectio and I'm having issue resolving the MSBuild properties. These are also documented in the source generator cookbook.
I made a simple Console application as a minimal reproducible example and initially added Injectio as a NuGet package which I then replaced with local Injectio project reference, so that it helps me debug the MSBuild properties and see what's wrong, more specifically this line of code:
public void Initialize(IncrementalGeneratorInitializationContext context)
{
if (!Debugger.IsAttached)
{
Debugger.Launch();
}
...
It ignores the property group below in my .csproj file. Why? Do I have to do CompilerVisibleProperty or something? This was also documented in the Injectio README, scroll down to the bottom.
<PropertyGroup>
<InjectioName>Library</InjectioName>
</PropertyGroup>
All this property is supposed to do is let me use custom name for the registrator instead of services.AddTest(), e.g. in this case it should be services.AddLibrary().
.ConfigureServices(services =>
{
services.AddTest(); // Expected: => services.AddLibrary()
})
Test.csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<PropertyGroup>
<InjectioName>Library</InjectioName>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Injectio" Version="1.0.33" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="7.0.0" />
</ItemGroup>
</Project>
Program.cs
using Injectio.Attributes;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
var host = new HostBuilder()
.ConfigureServices(services =>
{
services.AddTest();
})
.ConfigureLogging(x => x.AddConsole())
.UseConsoleLifetime()
.Build();
await host.RunAsync();
[RegisterSingleton(ServiceType = typeof(IHostedService))]
internal sealed class Worker : BackgroundService
{
private readonly ILogger<Worker> _logger;
private readonly PeriodicTimer _timer = new(TimeSpan.FromSeconds(10));
public Worker(ILogger<Worker> logger)
{
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (await _timer.WaitForNextTickAsync(stoppingToken))
{
try
{
_logger.LogInformation("Worker running at: {Time}", DateTimeOffset.Now);
}
catch (Exception ex)
{
_logger.LogError(ex, "Oh, no! Something bad happened");
}
}
}
}

It seems like I had to add CompilerVisibleProperty to the .csproj file, so it recognizes the MSBuild property.
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
</PropertyGroup>
<PropertyGroup>
<InjectioName>Library</InjectioName>
</PropertyGroup>
<ItemGroup>
<CompilerVisibleProperty Include="InjectioName" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Injectio" Version="1.0.33" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="7.0.0" />
</ItemGroup>
</Project>

Related

xUnit MessageSink for Collection Fixture does not generate output

I'm trying to add diagnostic output to my xUnit tests. For this, I'm using a combination of Collection Fixture and IMessageSink. This is my code:
using System;
using Xunit;
using Xunit.Abstractions;
using Xunit.Sdk;
namespace MessageSink
{
[Collection("My collection")]
public class UnitTest1
{
private readonly MyCollectionFixture _fixture;
public UnitTest1(MyCollectionFixture fixture)
{
_fixture = fixture;
}
[Fact]
public void Test1()
{
_fixture.Sink.OnMessage(new DiagnosticMessage("Hello World"));
}
}
public class MyCollectionFixture : IDisposable
{
public MyCollectionFixture(IMessageSink sink)
{
Sink = sink;
}
public IMessageSink Sink { get; }
public void Dispose()
{
}
}
[CollectionDefinition("My collection")]
public class MyCollection : ICollectionFixture<MyCollectionFixture>
{
}
}
Within the test project, I've created the following xunit.runner.json:
{
"$schema": "https://xunit.net/schema/current/xunit.runner.schema.json",
"diagnosticMessages": true
}
And this is my project configuration:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.9.4" />
<PackageReference Include="xunit" Version="2.4.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.3">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="coverlet.collector" Version="3.0.2">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<Content Include="xunit.runner.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
</Project>
I'd expect Hello World within the output of the test runner - but it is empty.
I (hopefully 🤞🏻) followed the docs in the correct way:
Shared Context between Tests
Capturing Output
Configuration Files
What am I doing wrong?
Thanks and cheers 👋🏻
You'll need to extend IClassFixture<MyCollectionFixture> to get that working for diagnostic messages.
For in-test messages, try using ITestOutputHelper which you can pass in into your test class along with MyCollectionFixture.
Check docs out: https://xunit.net/docs/capturing-output

ASP.NET Core WebApi Add-Migration Entity Framework Core

I'm trying to build a ASP.NET Core WebApi with Entity Framework Core and AutoMapper. When i try to use Add-Migration i get Exception has been thrown by the target of an invocation. at Microsoft.EntityFrameworkCore.Tools.Program.Main(String[] args)(I haven't made any changes to the Program class). I think the problem may be that the program cannot find the connection string.
This is my DataBaseContext Class:
public class DataBaseContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
.AddJsonFile("appsettings.json")
.Build();
optionsBuilder.UseSqlServer(configuration.GetConnectionString("DataBaseContext"));
}
public DataBaseContext(DbContextOptions<DataBaseContext> options) : base(options)
{
}
public DbSet<Director> Directors { get; set; }
public DbSet<Movie> Movies { get; set; }
}
This is appsettings.json:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"DataBaseContext": "Server=DESKTOP-LLPVCRN\\KISIELSQL;Database=KredekMovieManagement;Trusted_Connection=True;MultipleActiveResultSets=true"
}
}
This is Startup.cs:
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)
{
services.AddDbContext<DataBaseContext>(opt =>
opt.UseSqlServer("DataBaseContext"));
var config = new AutoMapper.MapperConfiguration(c =>
{
c.AddProfile(new MapperProfile());
});
var mapper = config.CreateMapper();
services.AddSingleton(mapper);
services.AddSingleton<IUserService, UserService>();
services.AddControllers();
}
//some code
}
}
This is someproject.csproj:
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AutoMapper" Version="10.1.1" />
<PackageReference Include="Microsoft.Bcl.AsyncInterfaces" Version="5.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="5.0.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="3.1.11" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.11" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.11">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="3.1.4" />
</ItemGroup>
</Project>
Because your project is a 3.1 version,your packages
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="5.0.2" />
are not compatible.
You need change it to:
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.11" />
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="3.1.11" />

adding nlog to .net core 3.0

adding nlog to .net core 3.0 application results in
'IServiceCollection' does not contain a definition for
'ConfigureLoggerService' and no accessible extension method
'ConfigureLoggerService' accepting a first argument of type
'IServiceCollection' could be found (are you missing a using directive
or an assembly reference?)
for Nuget I have
NLog.Extensions.Logging v1.6.1
NLog.Web.AspNetCore v4.9.0
in startup.cs
public Startup(IConfiguration config)
{
LogManager.LoadConfiguration(String.Concat(Directory.GetCurrentDirectory(), "/nlog.config"));
Configuration = config;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(IISDefaults.AuthenticationScheme);
services.AddMvc();
services.AddTransient<ICwopaAgencyFileRepository, CwopaAgencyFileRepository>();
services.AddTransient<ICurrentUserRepository, CurrentUserRepository>();
services.AddTransient<IUserRepository, UserRepository>();
services.AddTransient<IRevenueReceivedRepository, RevenueReceivedRepository>();
services.AddTransient<ILesseeRepository, LesseeRepository>();
services.AddTransient<ITractLesseeJunctionRepository, TractLesseeJunctionRepository>();
services.AddTransient<IPadRepository, PadRepository>();
services.AddTransient<IWellRepository, WellRepository>();
services.AddTransient<IWellOperarationRepository, WellOperationRepository>();
services.AddTransient<IRoyaltyRepository, RoyaltyRepository>();
services.AddTransient<IRoyaltyAdjustmentCardViewModelRepository, RoyaltyAdjustmentCardViewModelRepository>();
services.AddSingleton<ILoggerManager, LoggerService>();
string conString = Configuration["ConnectionStrings:DefaultConnection"];
services.AddDbContext<DataContext>(options =>
options.UseSqlServer(conString));
services.ConfigureLoggerService();
services.AddMvc(option => option.EnableEndpointRouting = false);
services.AddMemoryCache();
services.AddSession();
}
here is my csproj file
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup Label="Globals">
<SccProjectName>SAK</SccProjectName>
<SccProvider>SAK</SccProvider>
<SccAuxPath>SAK</SccAuxPath>
<SccLocalPath>SAK</SccLocalPath>
</PropertyGroup>
<PropertyGroup>
<TargetFramework>netcoreapp3.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.0.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="3.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.0.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="3.0.0" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="3.0.0" />
<PackageReference Include="NLog" Version="4.6.8" />
<PackageReference Include="NLog.Extensions.Logging" Version="1.6.1" />
<PackageReference Include="NLog.Web.AspNetCore" Version="4.9.0" />
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" />
</ItemGroup>
<ItemGroup>
<Folder Include="Migrations\" />
</ItemGroup>
</Project>
if you're following this tutorial, don't forget add this method extension
public static void ConfigureLoggerService(this IServiceCollection services)
{
services.AddSingleton<ILoggerManager, LoggerManager>();
}
because you're calling it in this line
services.ConfigureLoggerService();
Also, you can considere removing it, because you're registering this service LoggerService with the interface ILoggerManager.
Here are my steps:
1. Create a static class called ExceptionMiddlewareExtensions
2. Within ExceptionMiddlewareExtensions create a static function called ConfigureExpectionHandler.
3. In the start.cs - public void Configure - add the ILogger interface
4. In the start.cs, setup the dependency injection for ILogger, in ConfigureServices(IServiceCollection services). Create a serviceProvider then GetService based on ILogger<MyClassName>>(). Create a service singleton(type(ILogger),logger)
5. In the controller code, throw new Exception with message upon error condition
Create an Extension directory with the following class
public static class ExceptionMiddlewareExtensions
{
//public static void ConfigureExceptionHandler(this IApplicationBuilder app, ILoggerManager logger)
public static void ConfigureExceptionHandler(this IApplicationBuilder app, ILogger logger)
{
app.UseExceptionHandler(appError =>
{
appError.Run(async context =>
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
context.Response.ContentType = "application/json";
var contextFeature = context.Features.Get<IExceptionHandlerFeature>();
if (contextFeature != null)
{
logger.LogError($"Something went wrong: {contextFeature.Error}");
await context.Response.WriteAsync(new ErrorDetails()
{
StatusCode = context.Response.StatusCode,
Message = String.Format("Error: {0}", contextFeature.Error.Message)
}.ToString());
}
});
});
}
}
In Startup.cs added the following line
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger logger)
{
app.ConfigureExceptionHandler(logger);
}
In startup.cs add the following singleton
public void ConfigureServices(IServiceCollection services)
{
var serviceProvider = services.BuildServiceProvider();
var logger = serviceProvider.GetService<ILogger<ApplicationLogs>>();
services.AddSingleton(typeof(ILogger), logger);
}
in logs directory add the following class
public class ApplicationLogs
{
}
In the controller throw the Exception
public async Task<IActionResult> AddLoginView([FromBody] LoginView param)
{
if (error_condition)
{
throw new Exception("The user error messages");
}
}

ASP.NET Core authentication broken after upgrade to 3.0

I have the following code, which worked fine under ASP.NET Core 2.2 (edited to remove product-specific naming)
public class Type1AuthenticationOptions : AuthenticationSchemeOptions {
public string Secret { get; set; }
}
public class Type1AuthenticationHandler : AuthenticationHandler<Type1AuthenticationOptions> {
public Type1AuthenticationHandler (IOptionsMonitor<Type1AuthenticationOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock)
: base(options, logger, encoder, clock)
{ }
protected override Task<AuthenticateResult> HandleAuthenticateAsync() {
..
}
}
// Repeat for Type2AuthenticationHandler
My controllers were annotated thusly:
[Route("api/thing")]
[Authorize(AuthenticationSchemes = "type1")]
public class ThingController : Controller {
...
}
[Route("api/thing2")]
[Authorize(AuthenticationSchemes = "type2")] // different way of authorizing for thing2
public class Thing2Controller : Controller {
...
}
As above, this all worked great under Asp.NET Core 2.2 as well as prior version 2.1 and I think 2.0.
The key parts (Configure and ConfigureServices are below)
Upon upgrade to Asp.NET Core 3.0, the code all still compiles - all the classes, attributes and structure still exist, however my Authentication Handler is never getting called. If I put a breakpoint in the constructor of Type1AuthenticationHandler it doesn't even get hit.
My entire Configure() method method is as follows:
public void Configure(IApplicationBuilder app, Microsoft.AspNetCore.Hosting.IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseAuthentication();
app.UseAuthorization();
app.UseRouting();
app.UseEndpoints(endpoints => {
endpoints.MapControllers();
});
if (env.IsDevelopment()) {
app.UseDeveloperExceptionPage();
}
// Middleware to set the no-cache header value on ALL requests
app.Use((context, next) => {
context.Response.GetTypedHeaders().CacheControl = new CacheControlHeaderValue { NoCache = true };
return next();
});
And my ConfigureServices is
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
services.AddControllers() // no views to be had here. Turn it off for security
.AddNewtonsoftJson(opts => {
opts.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
opts.SerializerSettings.Converters.Add(new StringEnumConverter { NamingStrategy = new CamelCaseNamingStrategy() });
});
services
.AddAuthentication() // no default scheme, controllers must opt-in to authentication
.AddScheme<Type1AuthenticationOptions, Type1AuthenticationHandler>("type1", o =>
{
o.Secret = Configuration.GetThing1Secret();
})
.AddScheme<Type2AuthenticationOptions, Type2AuthenticationHandler>("type2", o =>
{
o.Secret = Configuration.GetThing2Secret();
});
services.AddAuthorization();
services.AddDbContext<DatabaseContext>(
options => options.UseNpgsql(Configuration.GetDatabaseConnectionString()),
ServiceLifetime.Transient);
// Used for fire and forget jobs that need access to the context outside of the
// the HTTP request that initiated the job
services.AddTransient(provider =>
new Func<DatabaseContext>(() => {
var options = new DbContextOptionsBuilder<DatabaseContext>()
.UseNpgsql(Configuration.GetDatabaseConnectionString())
.UseLoggerFactory(provider.GetRequiredService<ILoggerFactory>())
.Options;
return new DatabaseContext(options);
})
);
// make the configuration available to bits and pieces that may need it at runtime.
// Note: Generally it's bad practice to use this, you should configure your thing here, and inject the configured-thing instead
services.AddSingleton(Configuration);
services.AddMemoryCache();
// some more app-specific singleton services added but not relevant here
}
Any help much appreciated
P.S. on a long-shot, here's my csproj
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp3.0</TargetFramework>
<UserSecretsId>99f957da-757d-4749-bd65-2b86753821a6</UserSecretsId>
<!-- SonarQube needs this but it's otherwise irrelevant for dotnet core -->
<ProjectGuid>{39054410-1375-4163-95e9-00f08b2efe2e}</ProjectGuid>
</PropertyGroup>
<PropertyGroup>
<LangVersion>latest</LangVersion>
</PropertyGroup>
<ItemGroup>
<Folder Include="wwwroot\" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="AWSSDK.S3" Version="3.3.104.31" />
<PackageReference Include="AWSSDK.SimpleNotificationService" Version="3.3.101.68" />
<PackageReference Include="AWSSDK.SimpleSystemsManagement" Version="3.3.106.12" />
<PackageReference Include="Microsoft.AspNetCore.Hosting.WindowsServices" Version="3.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.0.0" PrivateAssets="all">
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.0.0" />
<PackageReference Include="AWSSDK.Extensions.NETCore.Setup" Version="3.3.100.1" />
<PackageReference Include="AWSSDK.SimpleEmail" Version="3.3.101.50" />
<PackageReference Include="NLog" Version="4.6.7" />
<PackageReference Include="NLog.Web.AspNetCore" Version="4.8.5" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="3.0.0-preview9" />
<PackageReference Include="Portable.BouncyCastle" Version="1.8.5" />
<PackageReference Include="System.IO.FileSystem.DriveInfo" Version="4.3.1" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="3.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Filter" Version="1.1.2" />
</ItemGroup>
</Project>
After taking another more detailed look at the migration guide, I noticed this:
If the app uses authentication/authorization features such as AuthorizePage or [Authorize], place the call to UseAuthentication and UseAuthorization after UseRouting (and after UseCors if CORS Middleware is used).
The trick (which is not mentioned in the migration guide) appears to be that UseAuthentication/UseAuthorization needs to be AFTER UseRouting but BEFORE UseEndpoints.
This works now:
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints => {
endpoints.MapControllers();
});
If you place the Auth calls after UseEndpoints then you get an error about missing middleware

Add migration error: No database provider has been configured for this DbContext

Adding migrations and updating database were working fine but seem to have hit a snag after updating to the latest version of Entity Framework core.
What am I missing?
Failing Command
add-migration authenticationtoken -Context ApplicationDbContext -verbose
ApplicationDbContext.cs
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
// I added this constructor after add-migration complained about
//needing a paramterless contructor.
public ApplicationDbContext()
{
}
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
...................
}
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options=> options.UseSqlServer(Configuration.GetConnectionString("SQLServerConnectionString")));
..............
}
Program.cs
public class Program
{
public static void Main(string[] args)
{
try
{
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseSerilog()
.Build()
.Run();
}
finally
{
Log.CloseAndFlush();
}
}
}
project.csproj:
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp2.2</TargetFramework>
<LangVersion>default</LangVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Braintree" Version="4.11.0" />
<PackageReference Include="BuildBundlerMinifier" Version="2.9.406" />
<PackageReference Include="Hangfire" Version="1.7.3" />
<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />
<PackageReference Include="Microsoft.Azure.Cosmos.Table" Version="1.0.1" />
<PackageReference Include="Microsoft.Azure.Storage.Blob" Version="10.0.3" />
<PackageReference Include="Microsoft.Azure.Storage.Common" Version="10.0.3" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.2.3" />
<PackageReference Include="morelinq" Version="3.1.1" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.2" />
<PackageReference Include="Sendgrid" Version="9.11.0" />
<PackageReference Include="Serilog.AspNetCore" Version="2.1.1" />
<PackageReference Include="Serilog.Extensions.Logging" Version="2.0.4" />
<PackageReference Include="Serilog.Settings.AppSettings" Version="2.2.2" />
<PackageReference Include="Serilog.Settings.Configuration" Version="3.0.1" />
<PackageReference Include="Serilog.Sinks.MSSqlServer" Version="5.1.2" />
<PackageReference Include="Stripe.net" Version="26.0.0" />
<PackageReference Include="Syncfusion.EJ2.AspNet.Core" Version="17.1.0.48" />
</ItemGroup>
</Project>
StackTrace:
System.InvalidOperationException: No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions<TContext> object in its constructor and passes it to the base constructor for DbContext.
at Microsoft.EntityFrameworkCore.Internal.DbContextServices.Initialize(IServiceProvider scopedProvider, IDbContextOptions contextOptions, DbContext context)
at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()
at Microsoft.EntityFrameworkCore.DbContext.Microsoft.EntityFrameworkCore.Infrastructure.IInfrastructure<System.IServiceProvider>.get_Instance()
at Microsoft.EntityFrameworkCore.Internal.InternalAccessorExtensions.GetService[TService](IInfrastructure`1 accessor)
at Microsoft.EntityFrameworkCore.Infrastructure.AccessorExtensions.GetService[TService](IInfrastructure`1 accessor)
at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(Func`1 factory)
at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)
at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigration.<>c__DisplayClass0_1.<.ctor>b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions<TContext> object in its constructor and passes it to the base constructor for DbContext.
Thank you #ivanStoev for your link, I was able to fix the issue by adding a public static CreateWebHostBuilder method, (which I had mistakenly refactored).
Program.cs:
public class Program
{
public static void Main(string[] args)
{
try
{
var iWebHost = CreateWebHostBuilder(args).Build();
Log.Information("Application starting");
iWebHost.Run();
}
catch (Exception exception)
{
Log.Error(exception.ToString());
}
finally
{
Log.CloseAndFlush();
}
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseSerilog();
}

Categories

Resources