I am currently upgrading a project from .NET Core RC1 to the new RTM 1.0 version. In RC1, there was a IApplicationEnvironment
which was replaced with IHostingEnvironment
in version 1.0
In RC1 I could do this
public class MyClass { protected static IApplicationEnvironment ApplicationEnvironment { get;private set; } public MyClass() { ApplicationEnvironment = PlatformServices.Default.Application; } }
Does anyone know how to achieve this in v1.0?
public class MyClass { protected static IHostingEnvironment HostingEnvironment { get;private set; } public MyClass() { HostingEnvironment = ???????????; } }
The IHostingEnvironment is an interface for . Net Core 2.0. The IHostingEnvironment interface need to be injected as dependency in the Controller and then later used throughout the Controller. The IHostingEnvironment interface have two properties.
You can mock the IHostEnvironment
using a mocking framework if needed or create a fake version by implementing the interface.
Give a class like this...
public class MyClass { protected IHostingEnvironment HostingEnvironment { get;private set; } public MyClass(IHostingEnvironment host) { HostingEnvironment = host; } }
You can setup a unit test example using Moq...
public void TestMyClass() { //Arrange var mockEnvironment = new Mock<IHostingEnvironment>(); //...Setup the mock as needed mockEnvironment .Setup(m => m.EnvironmentName) .Returns("Hosting:UnitTestEnvironment"); //...other setup for mocked IHostingEnvironment... //create your SUT and pass dependencies var sut = new MyClass(mockEnvironment.Object); //Act //...call you SUT //Assert //...assert expectations }
Using Microsoft.Extensions.Hosting
(which is one of the included packages in ASP.NET Core), you can use:
IHostEnvironment env = new HostingEnvironment { EnvironmentName = Environments.Development };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With