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

C# – Pad a 2D array on all sides

Padding a 2D array on all sides means adding new rows on the top and bottom, new columns on the left and right, and then copying the original elements to the center of the padded array. It looks like this: There are two approaches for copying the elements. You can either copy individual items in … Read more

ASP.NET Core – Log messages to the database in the background

I was reading about logging in ASP.NET when I came across this statement about logging to the database: When logging to SQL Server, don’t do so directly. Instead, add log messages to an in-memory queue and have a background worker dequeue and insert data to SQL Server. Paraphrased from https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-5.0#no-asynchronous-logger-methods In this article, I’ll show … Read more

How to stop the ASP.NET service when a background service crashes

When a background service throws an exception in ExecuteAsync() and stops running, nothing happens. No errors are logged, and the ASP.NET service continues to run. What if you want to stop the ASP.NET service when the background service crashes? To do that, you’ll need to handle exceptions in the background service and call IHostApplicationLifetime.StopApplication(), like … Read more

C# – How to supply IOptions

The options pattern is an indirect way to dependency inject settings into a registered service. If you’re using code that implements the options pattern, then you’re required to supply an IOptions<T> object. For example, let’s say you’re using the MovieService class and it has the following constructor: This requires you to supply the IOptions<MovieSettings> parameter. … Read more

ASP0000 Calling BuildServiceProvider from application code results in an additional copy of singleton services being created

When you try to call services.BuildServiceProvider(), you’ll get the following warning: Warning ASP0000 Calling ‘BuildServiceProvider’ from application code results in an additional copy of singleton services being created. Consider alternatives such as dependency injecting services as parameters to ‘Configure’. There are two scenarios where you may be calling BuildServiceProvider() because you want to resolve services … Read more

ASP.NET Core – Dependency inject a background service into the controllers

Let’s say you have a background service called DatabaseLoggerService. It runs as a hosted background service and logs messages to the database. It has the following definition: You want your controllers to use this for logging. They don’t need to know about the concrete DatabaseLoggerService class, and they don’t need to know they are actually … Read more

C# – How to batch read with Threading.ChannelReader

In a consumer/producer scenario, there are many reasons why you might want the consumer to read a batch of items. Maybe you’re bulk inserting items into SQL Server, or sending a payload with HttpClient. Sending lots of individual items over the network can be costly, and waiting for a full batch of items before sending … Read more

How to use NLog in ASP.NET

When you want to use NLog in ASP.NET, the first step is to install and configure NLog. Then you can either use NLog directly or fully integrate NLog and ASP.NET. Use NLog directly if you prefer to have static ILogger properties, instead of using dependency injection. The downside of this approach is that you’ll have … Read more

ASP.NET Core – How to unit test your middleware class

There are three requirements for unit testing a middleware class: Mock out RequestDelegate by defining a lambda that returns a Task (Task.FromException, Task.FromResult, or Task.FromCanceled). Mock out HttpContext by using DefaultHttpContext. The middleware function needs to be awaited, so your unit test needs to be defined with async Task. Here’s an example: This is a … Read more