Entity Framework Core health check

Health check are important, both of our selves, but also of ourrrrr micro-services. This is something I came across lately – a health check of your connection to a database via EF Core context. Let’s check this out!

To add a health check to EF Core you need a project:

  • WebAPI with .Net Core, I’m using 3.1
  • with Entity Framework Core and some DbContext

First install a nuget package

Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore

Now go to Startup.cs class and add this code in ConfigureServices method:

services
   .AddHealthChecks()
   .AddDbContextCheck<aspnetcoreContext>();

In the Configure method in the same class add:

app.UseEndpoints(endpoints =>
{
    endpoints.MapHealthChecks("/health");
});

Now run a service and go to endpoint /health, you should see:

Notice that I didn’t have to add any Controller class to make it work, it works out of the box.

But does it really check the database status? Now let’s break the connection string, and see what result will be:

So what it does underneath? Let’s check in SQL Server Profiles if it connects to DB.

So it really does call DB in this check – awesome.

Simple and effective. That’s how code should look like. You can find full code in my GitHub: https://github.com/mikuam/MichalBialecki.com.OData.Search 

Hope you enjoyed this, cheers!

 

 

One thought on “Entity Framework Core health check

  1. Randy Kreisel

    Did you use EF Core 3.x or 5.x?
    I initially used 3.x and it worked great. But when I moved to 5.x, I got this:

    Autofac.Core.DependencyResolutionException: An exception was thrown while activating HealthChecks.UI.Core.Data.HealthChecksDb.
    —> Autofac.Core.DependencyResolutionException: An exception was thrown while invoking the constructor ‘Void .ctor(Microsoft.EntityFrameworkCore.DbContextOptions`1[HealthChecks.UI.Core.Data.HealthChecksDb])’ on type ‘HealthChecksDb’.
    —> System.TypeLoadException: Method ‘CommitTransactionAsync’ in type ‘Microsoft.EntityFrameworkCore.InMemory.Storage.Internal.InMemoryTransactionManager’ from assembly ‘Microsoft.EntityFrameworkCore.InMemory, Version=3.1.3.0, Culture=neutral, PublicKeyToken=adb9793829ddae60’ does not have an implementation.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *