HCV- adding code–part 4
Now it is time to write some code . However, the implementation should be in a different class than the health check itself – to can be tested.
The code is as follows:
using System; using System.Collections.Generic; using System.Reflection; using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("TestHealthCheckVersion")] namespace HCVersion { internal class HCV { static Version versionEntry; static Version versionHCV; static HCV() { var ass = Assembly.GetEntryAssembly(); versionEntry = ass.GetName().Version; versionHCV = Assembly.GetExecutingAssembly().GetName().Version; } public string GetStartingAssemblyInformation() { return versionEntry.ToString(); } public string GetHCVAssemblyInformation() { return versionHCV.ToString(); } } }
The internals visible to is for running tests successfully.
The code for getting the real Health Check is
using Microsoft.Extensions.Diagnostics.HealthChecks; using System; using System.Collections.Generic; using System.Dynamic; using System.Threading; using System.Threading.Tasks; namespace HCVersion { public class HealthCheckVersion : IHealthCheck { public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default) { var hcv = new HCV(); var res = HealthCheckResult.Healthy(hcv.GetStartingAssemblyInformation(), new Dictionary<string, object>() { {"Entry",hcv.GetStartingAssemblyInformation() }, {"HCV",hcv.GetHCVAssemblyInformation() } }); return Task.FromResult( res); } } }
You will find the code at https://github.com/ignatandrei/HealthCheckVersion/releases/tag/testWorks
Leave a Reply