'IConfigurationBuilder' does not contain a definition for 'AddAzureAppConfiguration' - c#

Trying to setup Azure App Configuration with Azure Key Vault in Program.cs and getting following error:
'IConfigurationBuilder' does not contain a definition for
'AddAzureAppConfiguration'
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
webBuilder.ConfigureAppConfiguration((hostingContext, config) =>
{
var settings = config.Build();
config.AddAzureAppConfiguration(options =>
{
options.Connect(settings["ConnectionStrings:AppConfig"])
.ConfigureKeyVault(kv =>
{
kv.SetCredential(new DefaultAzureCredential());
});
});
})
.UseStartup<Startup>());

adding following package fixed it:
dotnet add package Microsoft.Azure.AppConfiguration.AspNetCore

Or even better:
dotnet add package Microsoft.Extensions.Configuration.AzureAppConfiguration

Clear and simple Microsoft Documentation for the App Config integration.

Related

Alternative of CreateDefaultBuilder in .NET 6 core

I don't want to use CreateDefaultBuilder and ConfigureWebHostDefaults in Program.cs file. Both of these functions make certain assumptions, that I am not comfortable with, also I don't want to rely on ASP.net defaults. I want to setup builder myself but don't know how to do that
I want to replace following code with my own builder
var host = Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration(builder =>
{
builder.Sources.Clear();
...
})
.ConfigureWebHostDefaults(webBuilder =>
{
...
})
.ConfigureServices((context, services) =>
services.Configure<...>(
context.Configuration.GetSection("...")))
.Build();
You can create an instance of HostBuilder directly:
var host = new HostBuilder()
.Build();
HostBuilder has a number of useful methods, such as ConfigureServices, ConfigureAppConfiguration, etc:
var host = new HostBuilder()
.ConfigureAppConfiguration(builder =>
{
// ...
})
.ConfigureServices((context, services) =>
{
// ...
})
.Build();
To configure the WebHost, without the defaults, use ConfigureWebHost:
var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
})
.Build();

Connection strings in .NET 6 Worker service

I am trying to connect to database with connection string which is written in appsetting.json. I try to pass it in UseSqlServer("...") in AddDbContext but it just doesn't work. When I write it in Context class it works.
So, program runs without errors but it doesn't connect to Db.
Does someone know what is wrong here?
Below is Program.cs code:
using IHost host = Host.CreateDefaultBuilder(args)
.UseWindowsService(options =>
{
options.ServiceName = "Subscriber Service";
})
.ConfigureServices(services =>
{
services.AddHostedService<DeliveryService>()
.AddSingleton<IQueueService, QueueService>()
.AddSingleton<IMailTransport, MailTransport>()
.AddSingleton<IHttpTransport, HttpTransport>()
.AddDbContext<nbiot_core_svctestContext>(
options => options.UseSqlServer("name=ConnectionStrings:DefaultConnection"));
})
.Build();
await host.RunAsync();
IHostBuilder.ConfigureServices accepts an action with two parameters, the first one is HostBuilderContext exposing configuration property (the one you are using comes from HostingHostBuilderExtensions), so try:
.ConfigureServices((ctx, services)=>
{
services
...
.AddDbContext<nbiot_core_svctestContext>(
options => options.UseSqlServer(ctx.Configuration.GetConnectionString("DefaultConnection"));
})

Get Configuration value from IHostBuilder in Net 6

I am creating a Worker application using Net 6 and I have in Program.cs:
IHostBuilder builder = Host.CreateDefaultBuilder(args);
builder.ConfigureHostConfiguration(x => {
x.AddJsonFile("settings.json", false, true);
x.AddJsonFile($"settings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", false, true);
x.AddEnvironmentVariables();
});
builder.UseSerilog(new LoggerBuilder(
new LoggerOptions {
ConnectionString = builder.Configuration.Get<Options>().ConnectionString
},
).CreateLogger());
In LoggerOptions I need to get Options and the ConnectionString from it.
I tried the following because that is what I do when using WebApplicationBuilder:
builder.Configuration.Get<Options>().ConnectionString
But this does not compile as it seems IHostBuilder does not have a Configuration property.
How can I do this?
Simple example:
var hostBuilder = Host.CreateDefaultBuilder(args);
hostBuilder.UseSerilog((hostContext, services) =>
{
var connectionString = hostContext.Configuration.GetConnectionString("MyConnectionString");
});
hostBuilder.ConfigureServices((hostContext, services) =>
{
var connectionString = hostContext.Configuration.GetConnectionString("MyConnectionString");
}
You can access it by using the configure services overload that accepts the HostBuilderContext. I don't typically use the LoggerBuilder:
IHost host = Host.CreateDefaultBuilder(args)
.UseSerilog((context, loggerConfiguration) =>
{
loggerConfiguration.ReadFrom.Configuration(context.Configuration);
})
.Build();
await host.RunAsync();

Why aren't my .NET Core log messages showing up in Azure?

I've tried various attempts at getting logging to show in Azure, but nothing is working. My latest attempt was this:
https://ardalis.com/configuring-logging-in-azure-app-services/
I added this to my project:
https://www.nuget.org/packages/Microsoft.Extensions.Logging.AzureAppServices
In Programs.cs, I did this:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>()
.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.AddConsole();
logging.AddAzureWebAppDiagnostics();
});
});
And I have this line in an API controller method that gets called:
_logger.LogWarning("Test warning logging.");
I also tried logging this way:
Trace.TraceWarning("Test warning logging (trace).");
My Azure App Service Logs settings look like this:
Yet, when I go to log stream, there are never any messages:
I'm at a lost as to what to try next.
In your Programs.cs, the ConfigureLogging(logging=>{xxx}) should not be placed within ConfigureWebHostDefaults. You should use the following code in your Programs.cs:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureLogging(logging=> {
logging.ClearProviders();
logging.AddConsole();
logging.AddAzureWebAppDiagnostics();
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
Then I'm using this line of code to send logs:
_logger.LogInformation("this is an information from index page...");
Then in azure portal, the message is there:

How to configure Azure logging after upgrading to ASP.NET Core 2.2

Are upgrading from ASP.NET Core 2.1 to ASP.NET Core 2.2 and following the official documentation guide.
Got a problem with writing the new logging configuration in Startup.cs. Specifically problems on how to handle the AzureWebAppDiagnostics.
The old configuration consisted of the following configuration:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
...
loggerFactory.AddApplicationInsights(app.ApplicationServices);
loggerFactory.AddAzureWebAppDiagnostics(
new AzureAppServicesDiagnosticsSettings
{
OutputTemplate = "{Timestamp:yyyy-MM-dd HH:mm:ss zzz} [{Level}] {RequestId}-{SourceContext}: {Message}{NewLine}{Exception}"
}
);
}
Both the AddAzureWebAppDiagnostics and the AzureAppServicesDiganosticsSettings is marked as obsolete. The later suggests to use AzureBlobLoggerOptions instead. The guide states that the logging config should be moved to something like this:
public void ConfigureServices(IServiceCollection services)
{
...
services.AddLogging(builder => builder
.AddConsole()
.AddAzureWebAppDiagnostics());
...
}
However I have no clue on how to properly add the configuration to the ILoggingBuildler AND as an extra bonus, the AzureBlobLoggerOptions does no allow for a custom OutputTemplate. The AddApplicationInsights is also missing from the ILoggingBuilder.
Any suggestions on how to get this working like it used to be?
In 2.2 I got this working by splitting the configuration between Program.cs and Startup.cs:
Add this to CreateWebHostBuilder in Program.cs:
.ConfigureLogging((hostingContext, logging) =>
{
logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
logging.AddConsole();
logging.AddDebug();
logging.AddEventSourceLogger();
logging.AddAzureWebAppDiagnostics();
})
Add this to ConfigureServices in Startup.cs:
services.Configure<AzureFileLoggerOptions>(options =>
{
options.FileName = "azure-diagnostics-";
options.FileSizeLimit = 50 * 1024;
options.RetainedFileCountLimit = 5;
});
This was enough for me to start seeing messages in the Azure App Service log; you need the Nuget package Microsoft.Extensions.Logging.AzureAppService and corresponding using statements also:
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Logging.AzureAppServices;
Insights is a bit slow to the party. There is a new package with support for the logging builder eg
<PackageReference Include="Microsoft.Extensions.Logging.ApplicationInsights" Version="2.9.0-beta3" />
Without that you will need to use the Obsolete way.
The custom OutputTemplate required a dependency on Serilog, which was removed for 2.2, so it's not in the file or blob options classes.
For 2.2 it's recommended to configure logging in Program.cs rather than Startup.cs; here's an example using AddAzureWebAppDiagnostics and the options classes:
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureLogging(logging => logging.AddAzureWebAppDiagnostics())
.ConfigureServices(serviceCollection => serviceCollection
.Configure<AzureFileLoggerOptions>(options => {
options.FileName = "azure-diagnostics-";
options.FileSizeLimit = 50 * 1024;
options.RetainedFileCountLimit = 5;
}).Configure<AzureBlobLoggerOptions>(options => {
options.BlobName = "log.txt";
}))
.UseStartup<Startup>();
This requires the NuGet package Microsoft.Extensions.Logging.AzureAppServices and the following using statements:
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.AzureAppServices;
using Microsoft.Extensions.Logging;

Categories