Profile Picture

Sirwan Afifi

Stories from a web developer.

© 2017. Sirwan Afifi All rights reserved.

Environments in ASP.NET Core

In ASP.NET Core we can have different hosting environments, this is supported by an environment variable called ASPNETCORE_ENVIRONMENT. You can see this value is already set to Development:

This value is active as long as you run your application inside Visual Studio, So when you deploy your application you must change this value. Actually, this value comes from a file called launchSettings.json:

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:13880/",
      "sslPort": 0
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "ProjectName": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

You can determine what the environment is by using IHostingEnvironment:

public void Configure(IApplicationBuilder app, 
	IHostingEnvironment env, ILoggerFactory loggerFactory)
{
	loggerFactory.AddConsole();

	if (env.IsDevelopment())
	{
		app.UseDeveloperExceptionPage();
	}
	else
	{
		app.UseExceptionHandler(new ExceptionHandlerOptions
		{
			ExceptionHandler = context => context.Response.WriteAsync("Opps!")
		});
	}

	// other configurations
}

This object also has a method called IsEnvironment for using custom environment:

if (env.IsEnvironment("envName"))
{
    // some config
}

One interesting thing is that the Startup class itself supports different environments, it means that for each environment you can have both Configure and ConfigureServices:

public void ConfigureDevelopment(IApplicationBuilder app, .....
public void ConfigureServicesDevelopment(IServiceCollection services)

public void ConfigureStaging(IApplicationBuilder app, .....
public void ConfigureServicesStaging(IServiceCollection services)

public void ConfigureProduction(IApplicationBuilder app, .....
public void ConfigureServicesProduction(IServiceCollection services)

Now you might ask how we can set this environment variable, well there are several ways that you can use, this great post explains them in details.

Getting to know Singleton pattern in C#

This pattern helps us to ensure a class has only one instance. The term comes from the mathematical concept of a singleton:

In mathematics, a singleton, also known as a unit set,[1] is a set with exactly one element. For example, the set {0} is a singleton.

Eventually we must have a class that only gives us a single instance:

var sigleInstance = MySingletonClass.GetInstance();

As you can see the only way to access the instance is by calling a public static method called GetInstance(), the single object instance under consideration is created only for the first time it is requested. suppose the following class:

public class MySingletonClass
{
    public MySingletonClass()
    {
	
    }
}

Now I want to make this class singleton, So the first step is to ensure that no one can instantiate our class for doing so we must make the constrauctor private:

public class MySingletonClass
{
    private MySingletonClass()
    {
	
    }
}

Now whenever you want to create a new instance of MySingletonClass using new keyword, Visual Studio gives you this error:

But we can still instantiate it from within the class. So next step is to create a new variable of type MySingletonClass inside the class, this class is going to be the only instance of the class:

public class MySingletonClass
{
	private static MySingletonClass _instance;

	private MySingletonClass() { }
}

So we are getting close to implementing the pattern. Now we need a way to get access the single instance. So we need a method like this:

public static MySingletonClass GetInstance()
{
	if (_instance == null)
	{
		_instance = new MySingletonClass();
	}
	return _instance;
}

This method instantiates MySingletonClass if an instance doesn’t already exist, otherwise it return the existing instance. To demonstrate the object lifetime we can print value of GetHashCode() fo these objects:

var mySingleInstance   = MySingletonClass.GetInstance();
var mySingleInstance_2 = MySingletonClass.GetInstance();
var mySingleInstance_3 = MySingletonClass.GetInstance();
var mySingleInstance_4 = MySingletonClass.GetInstance();

Console.WriteLine($"obj1: {mySingleInstance.GetHashCode()}");
Console.WriteLine($"obj2: {mySingleInstance_2.GetHashCode()} ");
Console.WriteLine($"obj3: {mySingleInstance_3.GetHashCode()} ");
Console.WriteLine($"obj4: {mySingleInstance_4.GetHashCode()} ");

As you can see all of the objects are the same and share the same instance. The problem with this implementation is that, it’s not thread-safe; it means that if seperate threads of execution access the _instance at the same time, more that one instance of the MySingletonClass object may be created. One of the solution is by using .NET 4’s Lazy<T> type:

public class MySingletonClass
{
	private static readonly Lazy<MySingletonClass> _instance = 
		new Lazy<MySingletonClass>(() => new MySingletonClass());

	private MySingletonClass() { }

	public static MySingletonClass GetInstance()
	{
		return _instance.Value;
	}
} 

Designing Fluent Interfaces in C#

The concept of Fluent Interface was coined by Martin Fowler to create various objects and wire them up together. This pattern is often used for object configuration and setup. For example in ASP.NET Core applications we have following code for configuring the server:

using System;
using Microsoft.AspNetCore.Hosting;

namespace aspnetcoreapp
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var host = new WebHostBuilder()
                .UseKestrel()
                .UseStartup<Startup>()
                .Build();

            host.Run();
        }
    }
}

As you can see we can chain methods together easily and the intention is to produce an API that is readable and flows. This pattern is heavily used in programming, Here’s an example of using this approach in jQuery:

$('#result')
	.css('background', 'yellow')
	.width(200)
	.height(200)
	.text('This is the result');

For C#, there is LINQ:

var person = PersonDataSource
	.Where(p => p.Age > 20)
	.OrderBy(p => p.Name)
	.Select(p => new {
		Name = p.Name,
		LastName = p.LastName
});

You might ask how to implement this pattern, well, it is very simple you just need to return this during method call. The Calculator defined below contains three methods. These methods are returing Calculator object using this keyword, which allow to chain the methods:

public class Calculator 
{
	public int Initial { get; private set; }
	public Calculator(int intial)
	{
		Initial = intial;
	}

	public Calculator Add(int x)
	{
		Initial = Initial + x;
		return this;
	}

	public Calculator Divide(int x)
	{
		Initial = Initial / x;
		return this;
	}

	public Calculator Substract(int x)
	{
		Initial = Initial - x;
		return this;
	}
}

Now we can use the class this way:

var calc = new Calculator(5)
			.Add(5)
			.Divide(5)
			.Substract(2);

System.Console.WriteLine(calc.Initial);

As you can see this approach makes our code concise and easier to read.