C# – Global exception event handlers

There are two global exception event available in all .NET applications: FirstChanceException: When any exception is thrown, this event is fired before anything else. UnhandledException: When there’s an unhandled exception, this event is fired right before the process is terminated. You wire up these event handlers in Main() (before anything else has executed), like this: … Read more

C# – How to load assemblies at runtime using Microsoft Extensibility Framework (MEF)

You can use Microsoft Extensibility Framework (MEF) to load assemblies at runtime. This is an alternative to implementing dynamic assembly loading with a more manual approach (like using AssemblyLoadContext). Here’s an example of using MEF to load an instance of IMessageProcessorPlugin from some assembly located in the C:\Plugins directory: MEF looks for exported types in … Read more

C# – How to unit test code that reads and writes to the console

When you’re unit testing code that uses the console IO methods, you’ll need a way to automate the input and a way to capture the output. There are two ways to do this: Redirect the console IO. Wrap the console IO method calls and mock out the wrapper. In this article, I’ll show how to … Read more

ASP.NET Core – Self-hosted service stub with a command line interface

When you’re integrating with a third-party API, you may want to send requests to a service stub instead of sending them to the real API. The purpose of a service stub is to simulate the third-party API by returning hardcoded responses. This is similar to how mocks are used in unit testing – it helps … Read more

C# – Parsing commands and arguments in a console app

In a console app there are two ways to get commands: Command line arguments passed into your program via Main(string[] args). User input from Console.ReadLine() (which you then split into a string[]). After getting a command, you have to parse it to figure out what code to execute. Typically commands have the following format: commandName … Read more

C# – Waiting for user input in a Console App

The following code shows how to wait for user input in a Console App: When the user types something in and presses the Enter key, Console.ReadLine() will return what they typed. Console.ReadLine() vs Console.ReadKey() Console.ReadLine() waits for the user to press Enter, and then returns everything they typed in. Console.ReadKey() returns individual key presses. It … Read more