Where is Asp.Net Core 3 source code for ConfigureWebHostDefaults? - asp.net-core-3.0

In Asp.Net Core 3, in the program.cs, the CreateHostBuilder method looks like this:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder => {
webBuilder.UseStartup<Startup>();
});
A key aspect of this method is the call to ConfigureWebHostDefaults that sets up all the hosting defaults since in 3.0 a generic Host is used rather than a WebHost as was the case in 2.x.
I would like to review the code for ConfigureWebHostDefaults so that I can get a better understanding of what web hosting defaults are used for 3.0. I've searched high and low on GitHub and can't seem to find the code. Where is the code for ConfigureWebHostDefaults ?
I would also love to know what you searched on to find it, or what approach you used to find it?

https://github.com/dotnet/aspnetcore/blob/release/3.0/src/DefaultBuilder/src/GenericHostBuilderExtensions.cs
However, that's merely slim wrapper. You really want:
https://github.com/dotnet/aspnetcore/blob/release/3.0/src/DefaultBuilder/src/WebHost.cs#L208
Which, conveniently, holds the source for CreateDefaultBuilder as well:
https://github.com/dotnet/aspnetcore/blob/release/3.0/src/DefaultBuilder/src/WebHost.cs#L155
I found this by simply cloning the repo, swapping to release/3.0 branch, running a search against the code base for "ConfigureWebHostDefaults", and so on.

Related

Why doesn’t IHostBuilder find the ConfigureWebHostDefaults method working with the Visual Studio’s Worker Service template?

I created a .NET 5, Visual Studio project using the Worker Service template, which creates a Program.cs file containing the Program class with the following method:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<Worker>();
});
Since I want to specify a Startup class to implement health checks for this application (since it will be deployed to Kubernetes (I’m following this tutorial)), I read there’s the ConfigureWebHostDefaults extension method. However, I get the following error trying to use it:
The code that gives me the error is the following (the one hidden by the error in the above screenshot):
.ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); })
This answer seemed to show my situation, but the Microsoft.Extensions.Hosting.Abstractions package doesn’t resolve the issue. I also tried to import the Microsoft.AspNetCore.Hosting and Microsoft.AspNetCore.Hosting packages, without success. I’m already using the Microsoft.Extensions.Hosting package.
I think it's still in the Microsoft.Extensions.Hosting namespace, but it's now in the Microsoft.AspNetCore assembly.
(The class containing the method is GenericHostBuilderExtensions).

How to add ApplicationInsights Logging Provider in Framework Console App Using Autofac

I am working on a .NET (full framework 4.7.1) console app that uses AutoFac for DI purposes.
We are in the process of migrating slowly to .NET Core, and have switched to using the ILogger abstractions provided by Microsoft.Extensions.Logging.Abstractions.
I have wired up ILogger<> and ILoggerFactory in AutoFac using the following
private static void RegisterLogging(ContainerBuilder builder)
{
builder.RegisterType<LoggerFactory>().As<ILoggerFactory>().SingleInstance();
builder.RegisterGeneric(typeof(Logger<>)).As(typeof(ILogger<>)).InstancePerDependency();
}
This depends on Microsoft.Extensions.Logging - and it seems to be working.
Now I want to wire up the Application Insights Logging provider, however all the documentation I can find only mentions how to add it to the .NET Core DI Container, and looking through the source code on various repos, I am a bit mystified on how to do it.
I figured that I might be able to do it like this:
builder.RegisterType<ApplicationInsightsLoggerProvider>().As<ILoggerProvider>();
But it depends on IOptions<TelemetryConfiguration> telemetryConfigurationOptions and IOptions<ApplicationInsightsLoggerOptions> applicationInsightsLoggerOptions neither of which I have.
Have anybody done this, or have suggestions on how to accomplish it?
I managed to get something going by doing it like this:
var serviceCollection = new ServiceCollection();
serviceCollection.AddLogging();
serviceCollection.AddApplicationInsightsTelemetryWorkerService();
builder.Populate(serviceCollection);
Not the very best solution, but I guess it does allow me to use the footwork of the ServiceCollection extensions methods, so I might have to live with that if nobdoy has a better answer

What is the .NET Core way of storing application settings?

I'm developing a cross-platform (win/mac/linux) application and I'm looking to store my application state. What is the .NET Core recommended way of doing this?
I've dug through the documentation and the closest thing I found was this, which is aimed at Visual Studio/.NET Framework (and I'm on VS Code).
There are 3 ways,
ONLY For Localhost
Simply stash them in your appsettings.json or as environment
variables.
For Staging / Production,
Azure Key Vault
By utilising Azure Key Vault and the Microsoft.Extensions.Configuration.AzureKeyVault NuGet Package, you will be able to stash configurations for your projects in the best way possible in the actual environment.
You then simply inject it in,
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((context, config) =>
{
var root = config.Build();
config.AddAzureKeyVault(
$”https://{root["KeyVault:Vault"]}.vault.azure.net/",
root[“KeyVault:ClientId”],
root[“KeyVault:ClientSecret”]);
})
.UseStartup<Startup>();
Although you still have to stash those 3 variables in, Azure has Azure AD to enforce access only to specified Applications. Thus, you need to register an application under the Azure AD in order for this to work. There are also restrictive features that will help you sandbox Azure Key Vault further.
Existing Vault Storages
Last but not least, the last way is to utilise existing vault storage options like HashiCorp. Libraries like https://github.com/rajanadar/VaultSharp will help you to implement it quickly and effectively. This is suitable for you if you primarily use a non-Azure provider for your servers.
As described here, you can use appsettings.json, which is generated and referenced within the new project template in dotnet new command
You can use the ConfigurationBuilder from the Microsoft.Extensions.Configuration nuget package
Although the docs are for ASP Core, you should be able to use them in your regular .Net Core app.
Create settings.json:
{
"mysetting": "value",
}
And use it:
var configuration = new ConfigurationBuilder()
.AddJsonFile("settings.json")
.Build();
// get the values from the settings.json
var mySetting = configuration["mysetting"];
Console.WriteLine(mySetting);

Setting Bugsnag configuration options in code

In the documentation it says that I can do the following in code to further configure my integration:
Each key provides an in code example and a config file example.
configuration.ReleaseStage = "development";
What I am trying to do is:
public static void Register(HttpConfiguration config)
{
var configuration = Bugsnag.ConfigurationSection.Configuration.Settings;
configuration.ReleaseStage = ConfigurationManager.AppSettings["Environment"];
config.UseBugsnag(configuration);
}
However, the configuration properties are read-only (don't have setters).
The alternative is to add the configurations to the Web.config:
<bugsnag apiKey="your-api-key" releaseStage="development">
The problem is that I am reading my environment from the AppSettings and therefore cannot do it this way.
Is it possible to do the configuration in code and if so, how?
UPDATE: Since posting the question I have found the issue on GitHub.
From the GitHub issue it seems as if this isn't possible so I used the work around suggested by one of the project's contributors.
The only work around I can suggest right now is to use the core Bugsnag nuget package...
I removed all the 'old' code, uninstalled all the NuGet packages except for the base Bugsnag and added the following code to the OnException override method where I had been logging exceptions up until now.
var configuration = new Configuration("API_KEY")
{
ReleaseStage = myReleaseStage
};
var client = new Bugsnag.Client(configuration);
client.Notify(new System.Exception("Error!"));
This worked and errors are now logged along with the environment in which they occurred. My next step will be to refactor this work around so that client is available globally but for now this solves my in code problem.
From Bugsnag's latest Go documentation, you can programmatically set the release stage. In your example, it would look like this:
configuration.ReleaseStage = ConfigurationManager.AppSettings["Environment"];

Caliburn.Micro IEventAggregator Publish method missing an overload

I'm working through some tutorials online learning Caliburn.Micro for the first time. Some of the tutorials are using the older 1.3.0 version, I'm using the newer 2.0.0.6 version which was the latest Nuget package which is likely the source of this discrepancy:
When trying to publish the following message:
public void Red()
{
_events.Publish(new ColorEvent(new SolidColorBrush(Colors.Red)));
}
The compiler throws an error saying that the overload wasn't found. The only overload for Publish that is available has the following signature:
void Publish(object message, Action marshal)
I got this to work by using the background worker thread method shown below but in my case it seems like overkill. Was the single parameter overload really removed from Caliburn.Micro?
Also, the documentation is here:
https://caliburnmicro.codeplex.com/wikipage?title=The%20Event%20Aggregator
still show examples using the more basic, single parameter example where you simply pass a message. Is the documentation at this link the latest that correctly describes 2.0.0.6?
public void Red()
{
_events.Publish(new ColorEvent(new SolidColorBrush(Colors.Red)),
action => Task.Factory.StartNew(action));
}
Finally, for bonus points:
What is this 2nd parameter good for other than publishing the message on a background thread? Can someone give some other example(s) of what this overload can be used for?
In Caliburn Micro version 2.0, the EventAggregator.Publish method also takes an action to marshal the event. To maintain the pre-2.0 behavior, you should switch to the EventAggregator.PublishOnUIThread method instead. See the migration instructions here for information on incompatibilities between 1.5 and 2.0.
In general, I believe that the Codeplex documentation is a little bit outdated. Please refer to the new dedicated web site for most up-to-date documentation.

Resources