C# – Circuit breaker with Polly

In an electrical system, a circuit breaker detects electrical problems and opens the circuit, which blocks electricity from flowing. To get electricity flowing again, you have to close the circuit. The same approach can be implemented in software when you’re sending requests to an external service. This is especially important when you’re sending lots of … Read more

C# – Global exception event handlers

There are two global exception events available in all .NET applications: You wire up these event handlers in Main() (before anything else has executed), like this: Note: If you’re using top-level statements, put these statements at the top of the ‘entry point’ file. This outputs the following before crashing: Notice the FirstChanceException event fired first. … 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 use Polly to do retries

Whenever you’re dealing with code that can run into transient errors, it’s a good idea to implement retries. Transient errors, by definition, are temporary and subsequent attempts should succeed. When you retry with a delay, it means you think the the transient error will go away by itself after a short period of time. When … Read more

How to do retries in EF Core

EF Core has built-in retry functionality. To use it, you can call options.EnableRetryOnFailure(), like this: The retry logic is contained in execution strategy classes. The above code is using the default execution strategy class (SqlServerRetryingExecutionStrategy). When you execute a query, it goes through the execution strategy class. It executes the query and checks for transient … Read more

C# – Using the is operator

You can use the is operator to check if an object is a certain type. Here’s an example: You can also use the is operator to declare a variable of the target type, like this: Note: The employee object is only available in the if block, but IntelliSense shows it out of its scope. If … 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

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

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

When you try to call BuildServiceProvider(), you 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

C# – Dependency inject BackgroundService into controllers

Let’s say you have a hosted BackgroundService called DatabaseLoggerService. It runs in the background and logs messages to the database. It has the following definition: You want your controllers to use this for logging. In other words, you want them to depend on ILoggerService, not the concrete DatabaseLoggerService class. First, constructor inject ILoggerService into your … Read more

Complex DataBinding accepts as a data source either an IList or an IListSource

If you try to set a list control’s DataSource to a type it can’t handle, then you’ll get the following exception: System.ArgumentException: Complex DataBinding accepts as a data source either an IList or an IListSource. (Parameter ‘value’)at System.Windows.Forms.ListControl.set_DataSource(Object value) Note: This applies to all controls that subclass ListControl, such as ComboBox and ListBox. This is … 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 it directly or fully integrate it 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: Here’s an example: This is a simple test that only checks the response status code. By passing in DefaultHttpContext, you have control over the request and response objects. You can set the request to whatever you need, and then verify the response. I’ll show examples … Read more

ASP.NET Core – How to add custom middleware

The ASP.NET Core request pipeline has middleware components (classes or lambdas) for processing requests. There are many built-in middleware components, such as AuthorizationMiddleware and HttpsRedirectionMiddleware. You can create custom middleware. I’ll show how below. 1 – Create middleware class In this example, I’ll show how to create a middleware class which is based on the … Read more