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

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

ASP.NET Core – Configure JSON serializer options

ASP.NET Core uses System.Text.Json as the default JSON serializer. To configure the JSON serializer options, call AddJsonOptions() in the initialization code: Calling AddJsonOptions() gives you access to the global JsonSerializerOptions object. This is used for all requests / responses. You can configure the options and add converters (including your own custom JSON converters). ASP.NET Core’s … Read more

How to use Newtonsoft in ASP.NET Core

By default, ASP.NET Core uses System.Text.Json for JSON serialization. If you want to use Newtonsoft instead: Note: Before .NET 6, do this in Startup.ConfigureServices(). Install the right package Microsoft packaged up Microsoft.AspNetCore.Mvc.NewtonsoftJson based on the framework version, so you can’t just install the latest package. You have to find the latest one for the framework … Read more

ASP.NET Core – How to unit test an ApiController

The key to unit testing an ApiController class is to mock out all of its dependencies, including the controller’s HttpContext property, like this: If the controller method you’re testing uses anything from the HttpContext, then you’ll want to swap in your own value. Otherwise HttpContext will be null and you’ll get a NullReferenceException. Fortunately Microsoft … Read more

Feature flags in ASP.NET Core

In this article, I’ll show an example of using a feature flag to toggle an endpoint on/off with a configuration value in appsettings.json. 1 – Install feature management package Install the Microsoft.FeatureManagement.AspNetCore package. Note: This is using (View > Other Windows > Package Manager Console). 2 – Add feature flags to appsettings.json Edit appsettings.json and … Read more

How to use BackgroundService in ASP.NET Core

You can use a hosted BackgroundService in ASP.NET Core for two purposes: In this article, I’ll show how to create and register a hosted BackgroundService. In this example, it periodically pings a URL and logs the results. 1 – Subclass BackgroundService The first step is to subclass BackgroundService: In this example, we’ll create a background … Read more

Error: Synchronous operations are disallowed

Problem When you try to do a synchronous IO operation in ASP.NET Core (such as writing to a file), you get the following exception: System.InvalidOperationException: ‘Synchronous operations are disallowed. Call WriteAsync or set AllowSynchronousIO to true The reason you’re getting this is because server option AllowSynchronousIO is false. Starting in ASP.NET Core 3.0, this is … Read more

ASP.NET – Async SSE endpoint

Server-Sent Events (SSE) allow a client to subscribe to messages on a server. The server pushes new messages to the client as they happen. This is an alternative to the client polling the server for new messages. In this article I’ll show how to implement the messaging system shown in the diagram below. This uses … Read more