-
Notifications
You must be signed in to change notification settings - Fork 5.1k
Description
Background and motivation
In 7.0-preview3 we made IHostEnvironment.ApplicationName
and IHostingEnvironment.ApplicationName
nullable because of the following:
runtime/src/libraries/Microsoft.Extensions.Hosting/src/HostBuilder.cs
Lines 202 to 213 in 05cb7f5
var hostingEnvironment = new HostingEnvironment() | |
{ | |
ApplicationName = hostConfiguration[HostDefaults.ApplicationKey], | |
EnvironmentName = hostConfiguration[HostDefaults.EnvironmentKey] ?? Environments.Production, | |
ContentRootPath = ResolveContentRootPath(hostConfiguration[HostDefaults.ContentRootKey], AppContext.BaseDirectory), | |
}; | |
if (string.IsNullOrEmpty(hostingEnvironment.ApplicationName)) | |
{ | |
// Note GetEntryAssembly returns null for the net4x console test runner. | |
hostingEnvironment.ApplicationName = Assembly.GetEntryAssembly()?.GetName().Name; | |
} |
While this is technically correct, it's not user friendly. Historically, applications have expected this property to be non-nullable like the other properties on the interface like EnvironmentName
.
It would be better if, similar to EnvironmentName
and "Production", we just pick a default ApplicationName
when Assembly.GetEntryAssembly()
returns null
.
API Proposal
namespace Microsoft.Extensions.Hosting;
public interface IHostEnvironment {
- string? ApplicationName { get; set; }
+ string ApplicationName { get; set; }
}
public interface IHostingEnvironment {
- string? ApplicationName { get; set; }
+ string ApplicationName { get; set; }
}
API Usage
Instead of doing complicated null-checks:
if (env.ApplicationName is not null)
{
var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));
if (appAssembly != null)
{
config.AddUserSecrets(appAssembly, optional: true);
}
}
We should be able to assume ApplicationName
is non-null:
var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));
if (appAssembly != null)
{
config.AddUserSecrets(appAssembly, optional: true);
}
Alternative Designs
Keeping ApplicationName
nullable.
Risks
We cannot come up with a good ApplicationName
for when Assembly.GetEntryAssembly()
returns null
.