2

In ASP.NET 5 core there is an interface, IHostingEnvironment, but looking at the samples and source code for ASP.NET there are 3 different ways to obtain an instance.

Using an attribute...

[FromServices]
public IHostingEnvironment HostingEnvironment { get; set; }

As an argument passed via the configure method in the Startup class...

public void Configure(IApplicationBuilder application, IHostingEnvironment environment)
{
}

Or by using DI with either of the following lines...

var hostingEnvironment = requestServices.GetService<IHostingEnvironment>();
var hostingEnvironment = app.ApplicationServices.GetRequiredService<IHostingEnvironment>();

What is not clear is which is the correct method to use.

As an example of how unclear it can be, if a call is made to a method which requires an instance of a class which implements the IHostingEnvironment from within the Startup class, should the instance be passed as an argument in the method call, should DI be used or something else?

Professor of programming
  • 2,978
  • 3
  • 30
  • 48

1 Answers1

0

After doing extensive research, I've came up with the following conclusion:

There are two main ways in which you may need to resovle dependencies:

  1. When creating an instance of a class using a constructor
  2. When invoking a method

1. When creating an instance of a class

Using an attribute...

[FromServices]
public IHostingEnvironment HostingEnvironment { get; set; }

This should be avoided (see the first link at the end of this answer), instead you should pass dependencies in the constructor so that you can see when a class has too many dependencies and therefore needs refactoring.

As an argument passed via the configure method in the Startup class...

public void Configure(IApplicationBuilder application, IHostingEnvironment environment)
{
}

You'll want to make sure the class you want to construct is registered with the DI container and then you would use DI to create an instance of the class (see the second link at the end of this answer).

Or by using DI...

var hostingEnvironment = app.ApplicationServices.GetRequiredService<IHostingEnvironment>();

This appears to be the preferred method for resolving dependencies because it ensures you never have to use the new keyword.

2. When invoking a method

In this instance, the dependency should be resolved in the constructor unless the method is not likely to be called, as for performance reasons you could want to delay the resolution of the dependency until the dependency is required.

If the dependency is resolved when the method is called, you are best off resolving the dependency outside of the method and pass it in as an argument using the interface for the type hint because this allows different types to be passed in the method call so that you are not limited to those registered as transients.

See the following links for more information:

Community
  • 1
  • 1
Professor of programming
  • 2,978
  • 3
  • 30
  • 48