C# .NET Core Filters

.NET Core Filters

Filters are used to implement reusable MVC pipeline logic that can be applied across the system, without writing that logic in all of your actions. Examples might be Exception handling, authorization, response caching etc. Filters intercept the stages of the MVC pipeline and allows us to run code before/after their executions.

There are different types of filters, and each happens in a different stage of the pipeline.

  • Authorization Filters run first to determine if the request is authorized and can short-circuit the pipeline if it is unauthorized.
  • Resource Filters are first after authorization. They can run code against the request on the way in and on the way out. Often used for caching or influencing the model binding. Can short-circuit the pipeline.
  • Action Filters are used to run code immediately before and/or immediately after the controller action. Can manipulate the arguments or results of the action.
  • Exception Filters are used go apply global policies to unhandled exceptions before anything is written to the response.
  • Result Filters are used to run code immediately before and/or after successful execution of action results. Useful for view formatting.

Filter Scopes

You can add a filter to request pipelines in 3 scope levels:

  • Globally using MvcOptions.Filters in ConfigureServices of your Startup
  • Controller level via Attributes
  • Specific action via Attributes
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc(options =>
    {
        options.Filters.Add(typeof(ExceptionFilter));
    });
}

As an attribute

public class ExceptionFilter : ExceptionFilterAttribute
{
    public override void OnException(ExceptionContext context)
    {
        ILogger logger = LogManager.GetLogger(context.ActionDescriptor?.DisplayName);

        logger.Error(context.Exception);
    }
}

On the Controller


[ExceptionFilter]
public class TestController : Controller
{
    // GET: api/test
    [HttpGet]
    public IEnumerable Get()
    {
        return View(new HomeViewModel());
    }
}

On the Action


public class TestController : Controller
{
    // GET: api/test
    [HttpGet]
    [ExceptionFilter]
    public IEnumerable Get()
    {
        return View(new HomeViewModel());
    }
}

You can set order on Filters with an Order property.
[ExceptionFilter, Order = 5]

Filters with the same Order run outside-in, meaning first global, then controller and then action-level filters are run.

Async / Sync Filters

Filter supports synchronous and asynchronous filters; The implementations use different interfaces.

Synchronous filters specify directly what happens in order using OnActionExecuting and OnActionExecuted. OnActionExecuting method is called before the action method and OnActionExecuted method is called after the action method.


public class CustomActionFilter : IActionFilter
    {
        public void OnActionExecuting(ActionExecutingContext context)
        {
            //To do : before the action executes
        }

        public void OnActionExecuted(ActionExecutedContext context)
        {
            //To do : after the action executes
        }
    }

Asynchronous filters are implemented with a single method, OnStageExecutionAsync


public class CustomAsyncActionFilter : IAsyncActionFilter
    {
        public async Task OnActionExecutionAsync(ActionExecutingContext context,
            ActionExecutionDelegate next)
        {
            //To do : before the action executes
            await next();
            //To do : after the action executes
        }
    }

.NET checks first for async filters, if found is called. If it is not found it calls the synchronous interface’s method(s). If both are implemented, the sync version will not be called.

Factory Pattern

What is the Factory Method Pattern?

Wikipedia describes it as:

In class-based programming, the factory method pattern is a creational pattern that uses factory methods to deal with the problem of creating objects without having to specify the exact class of the object that will be created. This is done by creating objects by calling a factory method—either specified in an interface and implemented by child classes, or implemented in a base class and optionally overridden by derived classes—rather than by calling a constructor.


The Factory Pattern moves and abstracts implementation details of similar classes or even a single class or struct that has many ways to implement or instantiate it and doesn’t require the user of that object to know about all the dependencies or how to construct it.

If the requirements for creating an object changed, and you were manually creating that object all over your application, you would have to update all usages of it if there was ever a change. Instead, leave that work up to the class that is building the object for you. Define a separate operation/method for creating the object/s.

This also enables us to create subclasses that can redefine how an object is created or even which subtype to instantiate.

Creating an object often requires complex processes not appropriate to include within a composing object. The object’s creation may lead to a significant duplication of code, may require information not accessible to the composing object, may not provide a sufficient level of abstraction, or may otherwise not be part of the composing object’s concerns. The factory method design pattern handles these problems by defining a separate method for creating the objects, which subclasses can then override to specify the derived type of product that will be created.


Let’s look at a simple example where we have a struct similar to .NETs TimeSpan object. It is just going to hold a number of ticks, but we may want to build up this Duration wrapper from several different lengths or units.

Examples are in C#.

public struct MyDuration {
  private readonly long ticks;
  public long Ticks { get { return ticks; } }

  // public MyDuration(long ticks) {
  //   this.ticks = ticks;
  // }

  private MyDuration(long ticks) {
    this.ticks = ticks;
  }

  public static MyDuration FromTicks(long ticks) {
    return new MyDuration(ticks);
  }

  public static MyDuration FromMilliseconds(long milliseconds) {
    return new MyDuration(milliseconds * 10000);
  }

  public static MyDuration FromSeconds(long seconds) {
    return new MyDuration(seconds * 10000 * 1000);
  }
}

public void main() {
  MyDuration duration = MyDuration.FromSeconds(5);
  // duration.Ticks == 50000000
}

You will also notice that I used a private constructor. Mixing the Factory Pattern with a traditional constructor can be confusing.

new MyDuration(5) //What does that mean?

Instead, use a private constructor, and use the same pattern for all use cases.

C#6 allows us to use named parameters, but I still like to lean towards consistency.

new MyDuration(ticks: 5)

Reminder, Pluralsight has many courses on different design patterns in many different languages and implementations, and they have a FREE trial!

Start a 10-day free trial at Pluralsight

Singleton Pattern

What is the Singleton Pattern?

Wikipedia describes it as:

In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.


Sometimes this is because we need shared state across the application, or for efficiency reasons – maybe for I/O operations. There are heavy debates on when or if you should even try to do this, but there are definitely use cases. Be careful when you have data/properties that need to be shared across a system through single instantiation, it may be a code smell. If it is what you need, here are some implementation details.

The biggest problems you are going to run into while implementing this pattern is thread safety. Let’s look a very straightforward, basic implementation of the Singleton.

Reminder, Pluralsight has many courses on different design patterns in many different languages and implementations, and they have a FREE trial!

Start a 10-day free trial at Pluralsight

Examples are in C#.

 public class Singleton {
  private static Singleton instance;
  private Singleton() {
    // Things that must only happen once
  }
  public static Singleton Instance() {
    if (instance == null)
    {
      instance = new Singleton()
    }
    return instance;
  }
  public void DoSomething() {
    // Must be thread safe
  }
}

We may run into threading issues where two threads try to access the constructor at the same time.


We could do some craziness like doing explicit thread locking and double checking.

 public class Singleton {
  private static Singleton instance;
  private static readonly object mutex = new object();
  private Singleton() {
    // Things that must only happen once
  }
  public static Singleton Instance() {
    if (instance == null) {
      lock (mutex) {
        if (instance == null)
        {
          instance = new Singleton()
        }
      }
    }
    return instance;
  }
  public void DoSomething() {
    // Must be thread safe
  }
}

Unless your class is very IO heavy or doing other heavy lifting, you probably won’t run into huge performance costs by thread locking, but it still isn’t very pretty, and can cause it’s own problems.


By understanding the mechanics of static classes and their static constructor, we can understand that .NET does a pretty good job of only letting one thread inside of a static constructor at a time, so an empty static constructor solves a lot of our problems and even forces a certain level of laziness in instantiation, but isn’t perfect.

static Singleton() {}

If being lazy is super important to you, you can go the extra mile and create an internal holder for your singleton.

 public class Singleton {
  private static class SingletonHolder {
    internal static readonly Singleton instance = new Singleton();
    // Empty static constructor forces laziness
    static SingletonHolder() {}
  }
  private Singleton() { Console.WriteLine("Instantiate") }
  public static Singleton Instance { get { return SingletonHolder.instance; } };
  // Stateless method
  public void SayHi() {
    Console.WriteLine("Hello");
  }
}

// Example usage
public void main() {
  Singleton.SayHi();
  Console.WriteLine("Before Usage");
  Singleton s = Singleton.Instance;

  /*
    Output:
    Hello
    Before Usage
    Instantiate
  */
}

In this example, simple methods that don’t need access to the internal state that you are trying to share across the application, don’t even need an instance of the class to execute and will not instantiate the class until you actually ask for the instance.


In .NET4 and later, you can use built-in language features to get real lazy implementation.

 public class Singleton {
  private static readonly Lazy lazyInstance =
    new Lazy(() => new Singleton(), isThreadSafe: true)
  private Singleton() {}
  public static Singleton Instance { get { return instance.Value; } };
  public void SayHi() {}
}