Skip to content

[API Proposal]: Make IHostEnvironment.ApplicationName non-nullable #68512

@halter73

Description

@halter73

Background and motivation

In 7.0-preview3 we made IHostEnvironment.ApplicationName and IHostingEnvironment.ApplicationName nullable because of the following:

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;
}

https://github.com/dotnet/runtime/pull/65403/files/dabdada197861a1fe343f0c82e6ebf3f87c663b5#r829310348

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);
}

See https://github.com/dotnet/aspnetcore/pull/40754/files#diff-ba47e8a57bffee356b71c57b0ac4709dc0eb1329d547a36ee30fea262cf8358c

Alternative Designs

Keeping ApplicationName nullable.

Risks

We cannot come up with a good ApplicationName for when Assembly.GetEntryAssembly() returns null.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions