SlideShare a Scribd company logo
1 of 51
Using dependency injection and
health checks in your
.NET Core solutions
Alex Thissen
Cloud architect at Xpirit, The Netherlands
Keeping entire system running
Determine state of entire system and intervene
How to know health status of individual services?
Collecting/correlating performance and health data
Sentry.ioRaygun.io RunscopeNewRelic AlertSite DataDogAppMetrics Azure Monitor
Centralized
Challenging
Doctor, am I sick? 12:34
Let's look at your vitals we
measured earlier:
- Pulse 60 per minute
- Blood pressure 130/80
12:34
Looks fine to me.
It seems you are healthy. 12:35
Thanks, doctor! 12:36
Let's look at your vitals we
measured:
- Pulse 180 per minute
- Blood pressure 150/110
12:34
Does not look good.
It seems you are unhealthy. 12:35
Modern medicine and health
Self-assessment
Context matters
You know best
Let's see. My vitals say:
- Pulse 180 per minute
- Blood pressure 150/110 12:34
How are you doing today?
12:36
Does not look good.
It seems I am unhealthy. 12:34
Oops, we need to do
something about that! 3:24
Good to know.
Stay healthy! 12:36
It's okay, as I am working out now
My back does not hurt.
So, I'm healthy!
12:34
Difference between metrics and health info
Metrics
Many individual measured values and counts
of events
Watch performance and trends
Useful for diagnostics and troubleshooting
Logic external to origin
Health
Intrinsic knowledge of implementation
required
DevOps mindset:
Logic to determine health is part of origin
Deployed together, good for autonomy
Availability
Latency
Internals
Simple Advanced
External dependencies
Readiness & liveliness
Preventive
Predicting
Examples
Healthy
• 200 OK
• "Everything is fine"
Degraded
• 200 OK
• "Could be doing
better or about to
become unhealthy"
Unhealthy
• 503 Service
Unavailable
• "Not able to perform"
ASP.NET Core application
/api/v1/… Middle
ware
New in .NET Core 2.2
Bootstrap health checks in
ASP.NET Core app
services.AddHealthChecks();
endpoints.MapHealthChecks("/health);
/health DefaultHealthCheckService
Microsoft.Extensions.Diagnostics.HealthChecks
.Abstractions
.EntityFramework
Microsoft.AspNetCore.Diagnostics.HealthChecks
What?
When?
How?
When a service is
unhealthy, how can you
trust its health status?public interface IHealthCheck
{
Task<HealthCheckResult> CheckHealthAsync(
HealthCheckContext context,
CancellationToken cancellationToken = default);
}
From: https://github.com/aspnet/Diagnostics/blob/master/src/
Microsoft.Extensions.Diagnostics.HealthChecks.Abstractions/HealthReport.cs
services
.AddHealthChecks()
.AddCheck("sync", () => … )
.AddAsyncCheck("async", async () => … )
.AddCheck<SqlConnectionHealthCheck>("SQL")
.AddCheck<UrlHealthCheck>("URL");
ASP.NET Core application
/health
DefaultHealthCheckService
Demo
ASP.NET Core 3.0 Health
object model
Health checks
Endpoints
Only 1 out-of-box check
DbContext
Build your own
IHealthCheck
Community packages
Xabaril/BeatPulse
Yours?AspNetCore.Diagnostics.HealthChecks.*
Microsoft.Extensions.Diagnostics.
HealthChecks.EntityFrameworkCore
services.AddHealthChecks()
.AddDbContextCheck<GamingDbContext>("EF")
Register multiple health endpoints
Middleware options
Register custom health check as singleton
/api/v1/…
/health
/ping
services.AddSingleton<KafkaHealthCheck>());
services.AddSingleton(new SqlConnectionHealthCheck(
new SqlConnection(Configuration.GetConnectionString("TestDB"))));
1. Customize health endpoint output for more details
2. Query endpoint(s)
3. Build user interface
Demo
A bit more advanced
Endpoints Frequency Locations Alerts
Pushes out health
info periodically
Options
ASP.NET Core application
DefaultHealthCheckService
HealthCheckPublisher
HostedService
IEnumerable<IHealthCheckPublisher>
services.AddHealthChecks()
.AddApplicationInsightsPublisher()
.AddPrometheusGatewayPublisher(
"http://pushgateway:9091/metrics",
"pushgateway") IHealthCheckPublisher
Registering a HealthCheckPublisher pre-.NET Core 3.0
// The following workaround permits adding an IHealthCheckPublisher
// instance to the service container when one or more other hosted
// services have already been added to the app. This workaround
// won't be required with the release of ASP.NET Core 3.0. For more
// information, see: https://github.com/aspnet/Extensions/issues/639.
services.TryAddEnumerable(
ServiceDescriptor.Singleton(typeof(IHostedService),
typeof(HealthCheckPublisherOptions).Assembly
.GetType(HealthCheckServiceAssembly)));
PrometheusGrafana
.NET Core app
Push
gateway
HealthCheckPublisher
HostedServiceNotification
channel
 Slack
 Telegram
 VictorOps
 PagerDuty
 …
Demo: Publishers
Prometheus and Grafana
Performance
MonitoringAvailability
Resiliency
Probing containers to check for availability and health
Kubernetes node
Kubernetes node
Kubernetes nodes
Containers
Readiness
Liveliness
1. Add health checks with tags
2. Register multiple endpoints
with filter using
Options predicate
/api/v1/…
/health
/health/ready
/health/lively
app.UseHealthChecks("/health/ready",
new HealthCheckOptions() {
Predicate = reg => reg.Tags.Contains("ready")
});
services.AddHealthChecks()
.AddCheck<CircuitBreakerHealthCheck>(
"circuitbreakers",
tags: new string[] { "ready" });
app.UseHealthChecks("/health/lively",
new HealthCheckOptions() {
Predicate = _ => true
});
Original pods only taken offline after new healthy one is up
Allows roll forward upgrades: Never roll back to previous version
Demo
Readiness and liveness
probes
Docker containers
Kubernetes
Expose as little detail as possible
Use different internal port
Add authentication using
middleware
Publish instead of endpoint
app.UseWhen(
ctx => ctx.User.Identity.IsAuthenticated,
a => a.UseHealthChecks("/securehealth")
);
1. Assume degraded state
2. Set short timeouts on checks
3. Avoid complicated health checks
4. Register health check as singletons in DI
/api/v1/…
/health
/ping
1. Unit testing
2. SOLID: Dependency
Inversion Principle
3. Loose coupling
4. Clean architecture
5. .NET Core is using it
Related
Domain
Logic
Presentation
From Jason Taylor: Clean Architecture with ASP.NET Core 2.2
Container HomeController
FloppyDiskRepository
IRepository
ILogger
ConsoleLogger
Possible ways to map
Try Add<ServiceType ImplementationType>
Builder pattern
Add TryAdd
ServiceType ImplementationType
Demo: ASP.NET Core DI
Quick look at how you were using
dependency injection all along
Register
• How
• Add… and TryAdd… of
type mappings
• Add… extension
methods
• Where
• Application root
• Startup class (ASP.NET)
Resolve
• Implicit
• Constructor injection
• ASP.NET Core specifics
• Explicit
• GetService<T>
• GetRequiredService<T>
• Also for enumerables
Release
• Automatic
• Resolved instances and
dependencies
• Scopes
• End of scope
• Might need to create
child scopes
IServiceCollection IServiceProvider IDisposable
1 2 3
Singleton
• Easy way to
implement
singleton pattern
• One instance per
DI container
• Beware of
concurrency and
threading issues
Scoped
• Duration of scope
• ASP.NET uses web request as scope
• Useful for UnitOfWork objects,
e.g. DbContext
• See also ServiceScopeFactory
Transient
• Single use
• Most common and safest
Typical startup in ASP.NET Core
public class Startup
{
public Startup(IConfiguration configuration, IHostEnvironment env)
public void ConfigureServices(IServiceCollection services)
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, …)
}
builder.UseStartup<Startup>();
1
2
3
Many ways to inject a
service instance
IServiceProvider
Pro tip
ActivatorUtilities
IServiceProvider
Register using
Configure(Services)
injection in Startup
class
Constructor
injection
[FromServices]
attribute
@inject
IApplicationBuilder.
ApplicationServices
HttpContext.
RequestServices
Middleware
Constructor or
Invoke method
Demo: Resolving services
in ASP.NET Core
Controller constructors
@inject
FromServicesAttribute
Application- and RequestServices
Hosting outside
and without ASP.NET Core
IHostedService
BackgroundService
Uses new Host, and
IHostBuilder for hosting
Startup
WebHostBuilder
HostBuilder Configure
Microsoft.Extensions.Hosting
Microsoft.Extensions.DependencyInjection
Resolved instances are released at end of scope
IDisposable Dispose
Create your own scopes with ServiceScopeFactory
Especially important for hosted services
AddHostedService<T>
using (var scope = serviceScopeFactory.CreateScope()) {
ISomeRepository scoped =
scope.ServiceProvider.GetRequiredService<ISomeRepository>();
await DoMyWork(scoped);
}
Check lifetime restrictions
Prevent memory leaks
and unexpected behavior
Host.CreateDefaultBuilder(args)
.UseDefaultServiceProvider((context, options) => {
options.ValidateScopes =
context.HostingEnvironment.IsDevelopment();
options.ValidateOnBuild = true; // .NET Core 3.0
})
Demo: Generic Host
New .NET Core 3.0 hosting
Scope validation
Using scopes
Too much abstractions
Conforming container
Easy to use anti-patterns
Microsoft.Extension.DependencyInjection
DefaultServiceProviderFactoryDuring configuring
ServiceDescriptors
IServiceProviderFactory<T>
CreateServiceProvider
CreateBuilder
ContainerBuilder
Build
System.ComponentModel.IServiceProvider
LightInjectServiceProviderFactory
During runtime ServiceProvider
GetService<T>
LightInjectServiceProvider
GetService<T>
IServiceContainer
Build
IServiceProviderFactory<T>
CreateServiceProvider
CreateBuilder
Plug in your favorite DI Framework
Option 1: While building host
UseServiceProviderFactory
ConfigureContainer
Option 2: When configuring services
ConfigureServices
IServiceProvider
Some alternative
DI Frameworks
Autofac
Castle Windsor
Lamar
LightInject
Ninject
SimpleInjector
Spring.NET
Unity
Demo: Advanced DI
Replacing DI container
Custom DI containers
Different registrations for environments
Configure{Environment}Services
Configure{Environment}
Startup{Environment} StartupProduction
Requires different startup
UseStartup<Startup>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder => {
var assembly = typeof(Startup).GetTypeInfo().Assembly;
webBuilder.UseStartup(assemblyName.GetName().Name);
});
Demo: Tips and tricks
Convention based startup
TestServer services override
Avoid use Service Locator pattern
IServiceProvider
IServiceScopeFactory.CreateScope
Do not directly inject HttpContext
IHttpContextAccessor
accessor.HttpContext.RequestServices
Avoid complex lifetime graphs
Dependency injection is
integral part of
.NET Core
If you do not like it,
replace it
Questions and Answers
Resources
https://docs.microsoft.com/en-us/azure/architecture/patterns/health-endpoint-monitoring
https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/health-checks
https://github.com/aspnet/Diagnostics/tree/master/src
https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-probes/
https://github.com/Xabaril/AspNetCore.Diagnostics.HealthChecks
https://github.com/alexthissen/healthmonitoring

More Related Content

What's hot

Modernizing to a Cloud Data Architecture
Modernizing to a Cloud Data ArchitectureModernizing to a Cloud Data Architecture
Modernizing to a Cloud Data ArchitectureDatabricks
 
AZ-900T00A-ENU-PowerPoint-02.pptx
AZ-900T00A-ENU-PowerPoint-02.pptxAZ-900T00A-ENU-PowerPoint-02.pptx
AZ-900T00A-ENU-PowerPoint-02.pptxTheGameSquad
 
Azure Data Factory | Moving On-Premise Data to Azure Cloud | Microsoft Azure ...
Azure Data Factory | Moving On-Premise Data to Azure Cloud | Microsoft Azure ...Azure Data Factory | Moving On-Premise Data to Azure Cloud | Microsoft Azure ...
Azure Data Factory | Moving On-Premise Data to Azure Cloud | Microsoft Azure ...Edureka!
 
Data Lakehouse, Data Mesh, and Data Fabric (r2)
Data Lakehouse, Data Mesh, and Data Fabric (r2)Data Lakehouse, Data Mesh, and Data Fabric (r2)
Data Lakehouse, Data Mesh, and Data Fabric (r2)James Serra
 
Databricks Platform.pptx
Databricks Platform.pptxDatabricks Platform.pptx
Databricks Platform.pptxAlex Ivy
 
Introduction to Modern Software Architecture
Introduction to Modern Software ArchitectureIntroduction to Modern Software Architecture
Introduction to Modern Software ArchitectureJérôme Kehrli
 
Cloud Scale Analytics Pitch Deck
Cloud Scale Analytics Pitch DeckCloud Scale Analytics Pitch Deck
Cloud Scale Analytics Pitch DeckNicholas Vossburg
 
Data Lakehouse Symposium | Day 4
Data Lakehouse Symposium | Day 4Data Lakehouse Symposium | Day 4
Data Lakehouse Symposium | Day 4Databricks
 
Microsoft Defender for Endpoint
Microsoft Defender for EndpointMicrosoft Defender for Endpoint
Microsoft Defender for EndpointCheah Eng Soon
 
Secure your Access to Cloud Apps using Microsoft Defender for Cloud Apps
Secure your Access to Cloud Apps using Microsoft Defender for Cloud AppsSecure your Access to Cloud Apps using Microsoft Defender for Cloud Apps
Secure your Access to Cloud Apps using Microsoft Defender for Cloud AppsVignesh Ganesan I Microsoft MVP
 
Migrate to Microsoft Azure with Confidence
Migrate to Microsoft Azure with ConfidenceMigrate to Microsoft Azure with Confidence
Migrate to Microsoft Azure with ConfidenceDavid J Rosenthal
 
Apache Kafka in the Transportation and Logistics
Apache Kafka in the Transportation and LogisticsApache Kafka in the Transportation and Logistics
Apache Kafka in the Transportation and LogisticsKai Wähner
 
Open Metadata and Governance with Apache Atlas
Open Metadata and Governance with Apache AtlasOpen Metadata and Governance with Apache Atlas
Open Metadata and Governance with Apache AtlasDataWorks Summit
 
Scaling and Modernizing Data Platform with Databricks
Scaling and Modernizing Data Platform with DatabricksScaling and Modernizing Data Platform with Databricks
Scaling and Modernizing Data Platform with DatabricksDatabricks
 
Azure data platform overview
Azure data platform overviewAzure data platform overview
Azure data platform overviewJames Serra
 
Data Lake Overview
Data Lake OverviewData Lake Overview
Data Lake OverviewJames Serra
 

What's hot (20)

Modernizing to a Cloud Data Architecture
Modernizing to a Cloud Data ArchitectureModernizing to a Cloud Data Architecture
Modernizing to a Cloud Data Architecture
 
AZ-900T00A-ENU-PowerPoint-02.pptx
AZ-900T00A-ENU-PowerPoint-02.pptxAZ-900T00A-ENU-PowerPoint-02.pptx
AZ-900T00A-ENU-PowerPoint-02.pptx
 
Azure Data Factory | Moving On-Premise Data to Azure Cloud | Microsoft Azure ...
Azure Data Factory | Moving On-Premise Data to Azure Cloud | Microsoft Azure ...Azure Data Factory | Moving On-Premise Data to Azure Cloud | Microsoft Azure ...
Azure Data Factory | Moving On-Premise Data to Azure Cloud | Microsoft Azure ...
 
Data Lakehouse, Data Mesh, and Data Fabric (r2)
Data Lakehouse, Data Mesh, and Data Fabric (r2)Data Lakehouse, Data Mesh, and Data Fabric (r2)
Data Lakehouse, Data Mesh, and Data Fabric (r2)
 
Architecting a datalake
Architecting a datalakeArchitecting a datalake
Architecting a datalake
 
Databricks Platform.pptx
Databricks Platform.pptxDatabricks Platform.pptx
Databricks Platform.pptx
 
Introduction to Modern Software Architecture
Introduction to Modern Software ArchitectureIntroduction to Modern Software Architecture
Introduction to Modern Software Architecture
 
Cloud Scale Analytics Pitch Deck
Cloud Scale Analytics Pitch DeckCloud Scale Analytics Pitch Deck
Cloud Scale Analytics Pitch Deck
 
Data Lakehouse Symposium | Day 4
Data Lakehouse Symposium | Day 4Data Lakehouse Symposium | Day 4
Data Lakehouse Symposium | Day 4
 
Azure migration
Azure migrationAzure migration
Azure migration
 
Microsoft Defender for Endpoint
Microsoft Defender for EndpointMicrosoft Defender for Endpoint
Microsoft Defender for Endpoint
 
Secure your Access to Cloud Apps using Microsoft Defender for Cloud Apps
Secure your Access to Cloud Apps using Microsoft Defender for Cloud AppsSecure your Access to Cloud Apps using Microsoft Defender for Cloud Apps
Secure your Access to Cloud Apps using Microsoft Defender for Cloud Apps
 
Migrate to Microsoft Azure with Confidence
Migrate to Microsoft Azure with ConfidenceMigrate to Microsoft Azure with Confidence
Migrate to Microsoft Azure with Confidence
 
Cloud Migration Workshop
Cloud Migration WorkshopCloud Migration Workshop
Cloud Migration Workshop
 
Apache Kafka in the Transportation and Logistics
Apache Kafka in the Transportation and LogisticsApache Kafka in the Transportation and Logistics
Apache Kafka in the Transportation and Logistics
 
Open Metadata and Governance with Apache Atlas
Open Metadata and Governance with Apache AtlasOpen Metadata and Governance with Apache Atlas
Open Metadata and Governance with Apache Atlas
 
Scaling and Modernizing Data Platform with Databricks
Scaling and Modernizing Data Platform with DatabricksScaling and Modernizing Data Platform with Databricks
Scaling and Modernizing Data Platform with Databricks
 
Azure data platform overview
Azure data platform overviewAzure data platform overview
Azure data platform overview
 
Data Lake Overview
Data Lake OverviewData Lake Overview
Data Lake Overview
 
IT Transformation with AWS
IT Transformation with AWSIT Transformation with AWS
IT Transformation with AWS
 

Similar to Health monitoring and dependency injection - CNUG November 2019

Alex Thissen "I don't feel so well… Integrating health checks in your .NET Co...
Alex Thissen "I don't feel so well… Integrating health checks in your .NET Co...Alex Thissen "I don't feel so well… Integrating health checks in your .NET Co...
Alex Thissen "I don't feel so well… Integrating health checks in your .NET Co...Fwdays
 
I dont feel so well. Integrating health checks in your .NET Core solutions - ...
I dont feel so well. Integrating health checks in your .NET Core solutions - ...I dont feel so well. Integrating health checks in your .NET Core solutions - ...
I dont feel so well. Integrating health checks in your .NET Core solutions - ...Alex Thissen
 
Come sta la nostra applicazione? Un viaggio alla scoperta degli Health Check ...
Come sta la nostra applicazione? Un viaggio alla scoperta degli Health Check ...Come sta la nostra applicazione? Un viaggio alla scoperta degli Health Check ...
Come sta la nostra applicazione? Un viaggio alla scoperta degli Health Check ...Andrea Dottor
 
SQL Server with CSharp WinForms.pdf
SQL Server with CSharp WinForms.pdfSQL Server with CSharp WinForms.pdf
SQL Server with CSharp WinForms.pdfMona686896
 
Resilience Engineering: A field of study, a community, and some perspective s...
Resilience Engineering: A field of study, a community, and some perspective s...Resilience Engineering: A field of study, a community, and some perspective s...
Resilience Engineering: A field of study, a community, and some perspective s...John Allspaw
 
Observability foundations in dynamically evolving architectures
Observability foundations in dynamically evolving architecturesObservability foundations in dynamically evolving architectures
Observability foundations in dynamically evolving architecturesBoyan Dimitrov
 
performancetestingjmeter-121109061704-phpapp02
performancetestingjmeter-121109061704-phpapp02performancetestingjmeter-121109061704-phpapp02
performancetestingjmeter-121109061704-phpapp02Gopi Raghavendra
 
performancetestingjmeter-121109061704-phpapp02 (1)
performancetestingjmeter-121109061704-phpapp02 (1)performancetestingjmeter-121109061704-phpapp02 (1)
performancetestingjmeter-121109061704-phpapp02 (1)QA Programmer
 
Principles and patterns for test driven development
Principles and patterns for test driven developmentPrinciples and patterns for test driven development
Principles and patterns for test driven developmentStephen Fuqua
 
Database continuous integration, unit test and functional test
Database continuous integration, unit test and functional testDatabase continuous integration, unit test and functional test
Database continuous integration, unit test and functional testHarry Zheng
 
Azure SQL Database - Connectivity Best Practices
Azure SQL Database - Connectivity Best PracticesAzure SQL Database - Connectivity Best Practices
Azure SQL Database - Connectivity Best PracticesJose Manuel Jurado Diaz
 
Sql storeprocedure
Sql storeprocedureSql storeprocedure
Sql storeprocedureftz 420
 
Websphere doctor - your guide to diagnose issues
Websphere doctor - your guide to diagnose issues Websphere doctor - your guide to diagnose issues
Websphere doctor - your guide to diagnose issues Joseph's WebSphere Library
 
Inside Logic Apps
Inside Logic AppsInside Logic Apps
Inside Logic AppsBizTalk360
 
Autonomous Transaction Processing (ATP): In Heavy Traffic, Why Drive Stick?
Autonomous Transaction Processing (ATP): In Heavy Traffic, Why Drive Stick?Autonomous Transaction Processing (ATP): In Heavy Traffic, Why Drive Stick?
Autonomous Transaction Processing (ATP): In Heavy Traffic, Why Drive Stick?Jim Czuprynski
 
Murach : How to work with session state and cookies
Murach : How to work with session state and cookiesMurach : How to work with session state and cookies
Murach : How to work with session state and cookiesMahmoudOHassouna
 
540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdf540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdfhamzadamani7
 

Similar to Health monitoring and dependency injection - CNUG November 2019 (20)

Alex Thissen "I don't feel so well… Integrating health checks in your .NET Co...
Alex Thissen "I don't feel so well… Integrating health checks in your .NET Co...Alex Thissen "I don't feel so well… Integrating health checks in your .NET Co...
Alex Thissen "I don't feel so well… Integrating health checks in your .NET Co...
 
I dont feel so well. Integrating health checks in your .NET Core solutions - ...
I dont feel so well. Integrating health checks in your .NET Core solutions - ...I dont feel so well. Integrating health checks in your .NET Core solutions - ...
I dont feel so well. Integrating health checks in your .NET Core solutions - ...
 
Come sta la nostra applicazione? Un viaggio alla scoperta degli Health Check ...
Come sta la nostra applicazione? Un viaggio alla scoperta degli Health Check ...Come sta la nostra applicazione? Un viaggio alla scoperta degli Health Check ...
Come sta la nostra applicazione? Un viaggio alla scoperta degli Health Check ...
 
SQL Server with CSharp WinForms.pdf
SQL Server with CSharp WinForms.pdfSQL Server with CSharp WinForms.pdf
SQL Server with CSharp WinForms.pdf
 
Resilience Engineering: A field of study, a community, and some perspective s...
Resilience Engineering: A field of study, a community, and some perspective s...Resilience Engineering: A field of study, a community, and some perspective s...
Resilience Engineering: A field of study, a community, and some perspective s...
 
Observability foundations in dynamically evolving architectures
Observability foundations in dynamically evolving architecturesObservability foundations in dynamically evolving architectures
Observability foundations in dynamically evolving architectures
 
performancetestingjmeter-121109061704-phpapp02
performancetestingjmeter-121109061704-phpapp02performancetestingjmeter-121109061704-phpapp02
performancetestingjmeter-121109061704-phpapp02
 
performancetestingjmeter-121109061704-phpapp02 (1)
performancetestingjmeter-121109061704-phpapp02 (1)performancetestingjmeter-121109061704-phpapp02 (1)
performancetestingjmeter-121109061704-phpapp02 (1)
 
Principles and patterns for test driven development
Principles and patterns for test driven developmentPrinciples and patterns for test driven development
Principles and patterns for test driven development
 
Database continuous integration, unit test and functional test
Database continuous integration, unit test and functional testDatabase continuous integration, unit test and functional test
Database continuous integration, unit test and functional test
 
AWS CodeDeploy
AWS CodeDeployAWS CodeDeploy
AWS CodeDeploy
 
Azure SQL Database - Connectivity Best Practices
Azure SQL Database - Connectivity Best PracticesAzure SQL Database - Connectivity Best Practices
Azure SQL Database - Connectivity Best Practices
 
Sql storeprocedure
Sql storeprocedureSql storeprocedure
Sql storeprocedure
 
Websphere doctor - your guide to diagnose issues
Websphere doctor - your guide to diagnose issues Websphere doctor - your guide to diagnose issues
Websphere doctor - your guide to diagnose issues
 
Inside Logic Apps
Inside Logic AppsInside Logic Apps
Inside Logic Apps
 
Autonomous Transaction Processing (ATP): In Heavy Traffic, Why Drive Stick?
Autonomous Transaction Processing (ATP): In Heavy Traffic, Why Drive Stick?Autonomous Transaction Processing (ATP): In Heavy Traffic, Why Drive Stick?
Autonomous Transaction Processing (ATP): In Heavy Traffic, Why Drive Stick?
 
Murach : How to work with session state and cookies
Murach : How to work with session state and cookiesMurach : How to work with session state and cookies
Murach : How to work with session state and cookies
 
540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdf540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdf
 
Unit Tesing in iOS
Unit Tesing in iOSUnit Tesing in iOS
Unit Tesing in iOS
 
Android L01 - Warm Up
Android L01 - Warm UpAndroid L01 - Warm Up
Android L01 - Warm Up
 

More from Alex Thissen

Go (con)figure - Making sense of .NET configuration
Go (con)figure - Making sense of .NET configurationGo (con)figure - Making sense of .NET configuration
Go (con)figure - Making sense of .NET configurationAlex Thissen
 
Logging, tracing and metrics: Instrumentation in .NET 5 and Azure
Logging, tracing and metrics: Instrumentation in .NET 5 and AzureLogging, tracing and metrics: Instrumentation in .NET 5 and Azure
Logging, tracing and metrics: Instrumentation in .NET 5 and AzureAlex Thissen
 
Logging tracing and metrics in .NET Core and Azure - dotnetdays 2020
Logging tracing and metrics in .NET Core and Azure - dotnetdays 2020Logging tracing and metrics in .NET Core and Azure - dotnetdays 2020
Logging tracing and metrics in .NET Core and Azure - dotnetdays 2020Alex Thissen
 
Architecting .NET solutions in a Docker ecosystem - .NET Fest Kyiv 2019
Architecting .NET solutions in a Docker ecosystem - .NET Fest Kyiv 2019Architecting .NET solutions in a Docker ecosystem - .NET Fest Kyiv 2019
Architecting .NET solutions in a Docker ecosystem - .NET Fest Kyiv 2019Alex Thissen
 
It depends: Loving .NET Core dependency injection or not
It depends: Loving .NET Core dependency injection or notIt depends: Loving .NET Core dependency injection or not
It depends: Loving .NET Core dependency injection or notAlex Thissen
 
Overview of the new .NET Core and .NET Platform Standard
Overview of the new .NET Core and .NET Platform StandardOverview of the new .NET Core and .NET Platform Standard
Overview of the new .NET Core and .NET Platform StandardAlex Thissen
 
Exploring Microservices in a Microsoft Landscape
Exploring Microservices in a Microsoft LandscapeExploring Microservices in a Microsoft Landscape
Exploring Microservices in a Microsoft LandscapeAlex Thissen
 
How Docker and ASP.NET Core will change the life of a Microsoft developer
How Docker and ASP.NET Core will change the life of a Microsoft developerHow Docker and ASP.NET Core will change the life of a Microsoft developer
How Docker and ASP.NET Core will change the life of a Microsoft developerAlex Thissen
 
Visual Studio Productivity tips
Visual Studio Productivity tipsVisual Studio Productivity tips
Visual Studio Productivity tipsAlex Thissen
 
Exploring microservices in a Microsoft landscape
Exploring microservices in a Microsoft landscapeExploring microservices in a Microsoft landscape
Exploring microservices in a Microsoft landscapeAlex Thissen
 
Asynchronous programming in ASP.NET
Asynchronous programming in ASP.NETAsynchronous programming in ASP.NET
Asynchronous programming in ASP.NETAlex Thissen
 
Visual Studio 2015 experts tips and tricks
Visual Studio 2015 experts tips and tricksVisual Studio 2015 experts tips and tricks
Visual Studio 2015 experts tips and tricksAlex Thissen
 
ASP.NET 5 - Microsoft's Web development platform reimagined
ASP.NET 5 - Microsoft's Web development platform reimaginedASP.NET 5 - Microsoft's Web development platform reimagined
ASP.NET 5 - Microsoft's Web development platform reimaginedAlex Thissen
 
MVC 6 - the new unified Web programming model
MVC 6 - the new unified Web programming modelMVC 6 - the new unified Web programming model
MVC 6 - the new unified Web programming modelAlex Thissen
 
Run your Dockerized ASP.NET application on Windows and Linux!
Run your Dockerized ASP.NET application on Windows and Linux!Run your Dockerized ASP.NET application on Windows and Linux!
Run your Dockerized ASP.NET application on Windows and Linux!Alex Thissen
 
.NET Core: a new .NET Platform
.NET Core: a new .NET Platform.NET Core: a new .NET Platform
.NET Core: a new .NET PlatformAlex Thissen
 

More from Alex Thissen (18)

Go (con)figure - Making sense of .NET configuration
Go (con)figure - Making sense of .NET configurationGo (con)figure - Making sense of .NET configuration
Go (con)figure - Making sense of .NET configuration
 
Logging, tracing and metrics: Instrumentation in .NET 5 and Azure
Logging, tracing and metrics: Instrumentation in .NET 5 and AzureLogging, tracing and metrics: Instrumentation in .NET 5 and Azure
Logging, tracing and metrics: Instrumentation in .NET 5 and Azure
 
Logging tracing and metrics in .NET Core and Azure - dotnetdays 2020
Logging tracing and metrics in .NET Core and Azure - dotnetdays 2020Logging tracing and metrics in .NET Core and Azure - dotnetdays 2020
Logging tracing and metrics in .NET Core and Azure - dotnetdays 2020
 
Architecting .NET solutions in a Docker ecosystem - .NET Fest Kyiv 2019
Architecting .NET solutions in a Docker ecosystem - .NET Fest Kyiv 2019Architecting .NET solutions in a Docker ecosystem - .NET Fest Kyiv 2019
Architecting .NET solutions in a Docker ecosystem - .NET Fest Kyiv 2019
 
It depends: Loving .NET Core dependency injection or not
It depends: Loving .NET Core dependency injection or notIt depends: Loving .NET Core dependency injection or not
It depends: Loving .NET Core dependency injection or not
 
Overview of the new .NET Core and .NET Platform Standard
Overview of the new .NET Core and .NET Platform StandardOverview of the new .NET Core and .NET Platform Standard
Overview of the new .NET Core and .NET Platform Standard
 
Exploring Microservices in a Microsoft Landscape
Exploring Microservices in a Microsoft LandscapeExploring Microservices in a Microsoft Landscape
Exploring Microservices in a Microsoft Landscape
 
How Docker and ASP.NET Core will change the life of a Microsoft developer
How Docker and ASP.NET Core will change the life of a Microsoft developerHow Docker and ASP.NET Core will change the life of a Microsoft developer
How Docker and ASP.NET Core will change the life of a Microsoft developer
 
Visual Studio Productivity tips
Visual Studio Productivity tipsVisual Studio Productivity tips
Visual Studio Productivity tips
 
Exploring microservices in a Microsoft landscape
Exploring microservices in a Microsoft landscapeExploring microservices in a Microsoft landscape
Exploring microservices in a Microsoft landscape
 
Asynchronous programming in ASP.NET
Asynchronous programming in ASP.NETAsynchronous programming in ASP.NET
Asynchronous programming in ASP.NET
 
Visual Studio 2015 experts tips and tricks
Visual Studio 2015 experts tips and tricksVisual Studio 2015 experts tips and tricks
Visual Studio 2015 experts tips and tricks
 
ASP.NET 5 - Microsoft's Web development platform reimagined
ASP.NET 5 - Microsoft's Web development platform reimaginedASP.NET 5 - Microsoft's Web development platform reimagined
ASP.NET 5 - Microsoft's Web development platform reimagined
 
MVC 6 - the new unified Web programming model
MVC 6 - the new unified Web programming modelMVC 6 - the new unified Web programming model
MVC 6 - the new unified Web programming model
 
//customer/
//customer///customer/
//customer/
 
ASP.NET vNext
ASP.NET vNextASP.NET vNext
ASP.NET vNext
 
Run your Dockerized ASP.NET application on Windows and Linux!
Run your Dockerized ASP.NET application on Windows and Linux!Run your Dockerized ASP.NET application on Windows and Linux!
Run your Dockerized ASP.NET application on Windows and Linux!
 
.NET Core: a new .NET Platform
.NET Core: a new .NET Platform.NET Core: a new .NET Platform
.NET Core: a new .NET Platform
 

Recently uploaded

Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Neo4j
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsAndrey Dotsenko
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 

Recently uploaded (20)

Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 

Health monitoring and dependency injection - CNUG November 2019

  • 1. Using dependency injection and health checks in your .NET Core solutions Alex Thissen Cloud architect at Xpirit, The Netherlands
  • 2. Keeping entire system running Determine state of entire system and intervene How to know health status of individual services? Collecting/correlating performance and health data Sentry.ioRaygun.io RunscopeNewRelic AlertSite DataDogAppMetrics Azure Monitor
  • 3. Centralized Challenging Doctor, am I sick? 12:34 Let's look at your vitals we measured earlier: - Pulse 60 per minute - Blood pressure 130/80 12:34 Looks fine to me. It seems you are healthy. 12:35 Thanks, doctor! 12:36 Let's look at your vitals we measured: - Pulse 180 per minute - Blood pressure 150/110 12:34 Does not look good. It seems you are unhealthy. 12:35
  • 4. Modern medicine and health Self-assessment Context matters You know best Let's see. My vitals say: - Pulse 180 per minute - Blood pressure 150/110 12:34 How are you doing today? 12:36 Does not look good. It seems I am unhealthy. 12:34 Oops, we need to do something about that! 3:24 Good to know. Stay healthy! 12:36 It's okay, as I am working out now My back does not hurt. So, I'm healthy! 12:34
  • 5. Difference between metrics and health info Metrics Many individual measured values and counts of events Watch performance and trends Useful for diagnostics and troubleshooting Logic external to origin Health Intrinsic knowledge of implementation required DevOps mindset: Logic to determine health is part of origin Deployed together, good for autonomy
  • 7. Healthy • 200 OK • "Everything is fine" Degraded • 200 OK • "Could be doing better or about to become unhealthy" Unhealthy • 503 Service Unavailable • "Not able to perform"
  • 8. ASP.NET Core application /api/v1/… Middle ware New in .NET Core 2.2 Bootstrap health checks in ASP.NET Core app services.AddHealthChecks(); endpoints.MapHealthChecks("/health); /health DefaultHealthCheckService Microsoft.Extensions.Diagnostics.HealthChecks .Abstractions .EntityFramework Microsoft.AspNetCore.Diagnostics.HealthChecks
  • 9. What? When? How? When a service is unhealthy, how can you trust its health status?public interface IHealthCheck { Task<HealthCheckResult> CheckHealthAsync( HealthCheckContext context, CancellationToken cancellationToken = default); } From: https://github.com/aspnet/Diagnostics/blob/master/src/ Microsoft.Extensions.Diagnostics.HealthChecks.Abstractions/HealthReport.cs
  • 10. services .AddHealthChecks() .AddCheck("sync", () => … ) .AddAsyncCheck("async", async () => … ) .AddCheck<SqlConnectionHealthCheck>("SQL") .AddCheck<UrlHealthCheck>("URL"); ASP.NET Core application /health DefaultHealthCheckService
  • 11. Demo ASP.NET Core 3.0 Health object model Health checks Endpoints
  • 12. Only 1 out-of-box check DbContext Build your own IHealthCheck Community packages Xabaril/BeatPulse Yours?AspNetCore.Diagnostics.HealthChecks.* Microsoft.Extensions.Diagnostics. HealthChecks.EntityFrameworkCore services.AddHealthChecks() .AddDbContextCheck<GamingDbContext>("EF")
  • 13. Register multiple health endpoints Middleware options Register custom health check as singleton /api/v1/… /health /ping services.AddSingleton<KafkaHealthCheck>()); services.AddSingleton(new SqlConnectionHealthCheck( new SqlConnection(Configuration.GetConnectionString("TestDB"))));
  • 14. 1. Customize health endpoint output for more details 2. Query endpoint(s) 3. Build user interface
  • 15. Demo A bit more advanced
  • 17. Pushes out health info periodically Options ASP.NET Core application DefaultHealthCheckService HealthCheckPublisher HostedService IEnumerable<IHealthCheckPublisher> services.AddHealthChecks() .AddApplicationInsightsPublisher() .AddPrometheusGatewayPublisher( "http://pushgateway:9091/metrics", "pushgateway") IHealthCheckPublisher
  • 18. Registering a HealthCheckPublisher pre-.NET Core 3.0 // The following workaround permits adding an IHealthCheckPublisher // instance to the service container when one or more other hosted // services have already been added to the app. This workaround // won't be required with the release of ASP.NET Core 3.0. For more // information, see: https://github.com/aspnet/Extensions/issues/639. services.TryAddEnumerable( ServiceDescriptor.Singleton(typeof(IHostedService), typeof(HealthCheckPublisherOptions).Assembly .GetType(HealthCheckServiceAssembly)));
  • 22. Probing containers to check for availability and health Kubernetes node Kubernetes node Kubernetes nodes Containers Readiness Liveliness
  • 23. 1. Add health checks with tags 2. Register multiple endpoints with filter using Options predicate /api/v1/… /health /health/ready /health/lively app.UseHealthChecks("/health/ready", new HealthCheckOptions() { Predicate = reg => reg.Tags.Contains("ready") }); services.AddHealthChecks() .AddCheck<CircuitBreakerHealthCheck>( "circuitbreakers", tags: new string[] { "ready" }); app.UseHealthChecks("/health/lively", new HealthCheckOptions() { Predicate = _ => true });
  • 24. Original pods only taken offline after new healthy one is up Allows roll forward upgrades: Never roll back to previous version
  • 26. Expose as little detail as possible Use different internal port Add authentication using middleware Publish instead of endpoint app.UseWhen( ctx => ctx.User.Identity.IsAuthenticated, a => a.UseHealthChecks("/securehealth") );
  • 27. 1. Assume degraded state 2. Set short timeouts on checks 3. Avoid complicated health checks 4. Register health check as singletons in DI
  • 29. 1. Unit testing 2. SOLID: Dependency Inversion Principle 3. Loose coupling 4. Clean architecture 5. .NET Core is using it Related Domain Logic Presentation From Jason Taylor: Clean Architecture with ASP.NET Core 2.2
  • 31. Possible ways to map Try Add<ServiceType ImplementationType> Builder pattern Add TryAdd ServiceType ImplementationType
  • 32. Demo: ASP.NET Core DI Quick look at how you were using dependency injection all along
  • 33. Register • How • Add… and TryAdd… of type mappings • Add… extension methods • Where • Application root • Startup class (ASP.NET) Resolve • Implicit • Constructor injection • ASP.NET Core specifics • Explicit • GetService<T> • GetRequiredService<T> • Also for enumerables Release • Automatic • Resolved instances and dependencies • Scopes • End of scope • Might need to create child scopes IServiceCollection IServiceProvider IDisposable 1 2 3
  • 34. Singleton • Easy way to implement singleton pattern • One instance per DI container • Beware of concurrency and threading issues Scoped • Duration of scope • ASP.NET uses web request as scope • Useful for UnitOfWork objects, e.g. DbContext • See also ServiceScopeFactory Transient • Single use • Most common and safest
  • 35. Typical startup in ASP.NET Core public class Startup { public Startup(IConfiguration configuration, IHostEnvironment env) public void ConfigureServices(IServiceCollection services) public void Configure(IApplicationBuilder app, IWebHostEnvironment env, …) } builder.UseStartup<Startup>(); 1 2 3
  • 36. Many ways to inject a service instance IServiceProvider Pro tip ActivatorUtilities IServiceProvider Register using Configure(Services) injection in Startup class Constructor injection [FromServices] attribute @inject IApplicationBuilder. ApplicationServices HttpContext. RequestServices Middleware Constructor or Invoke method
  • 37. Demo: Resolving services in ASP.NET Core Controller constructors @inject FromServicesAttribute Application- and RequestServices
  • 38. Hosting outside and without ASP.NET Core IHostedService BackgroundService Uses new Host, and IHostBuilder for hosting Startup WebHostBuilder HostBuilder Configure Microsoft.Extensions.Hosting Microsoft.Extensions.DependencyInjection
  • 39. Resolved instances are released at end of scope IDisposable Dispose Create your own scopes with ServiceScopeFactory Especially important for hosted services AddHostedService<T> using (var scope = serviceScopeFactory.CreateScope()) { ISomeRepository scoped = scope.ServiceProvider.GetRequiredService<ISomeRepository>(); await DoMyWork(scoped); }
  • 40. Check lifetime restrictions Prevent memory leaks and unexpected behavior Host.CreateDefaultBuilder(args) .UseDefaultServiceProvider((context, options) => { options.ValidateScopes = context.HostingEnvironment.IsDevelopment(); options.ValidateOnBuild = true; // .NET Core 3.0 })
  • 41. Demo: Generic Host New .NET Core 3.0 hosting Scope validation Using scopes
  • 42. Too much abstractions Conforming container Easy to use anti-patterns
  • 44. Plug in your favorite DI Framework Option 1: While building host UseServiceProviderFactory ConfigureContainer Option 2: When configuring services ConfigureServices IServiceProvider Some alternative DI Frameworks Autofac Castle Windsor Lamar LightInject Ninject SimpleInjector Spring.NET Unity
  • 45. Demo: Advanced DI Replacing DI container Custom DI containers
  • 46. Different registrations for environments Configure{Environment}Services Configure{Environment} Startup{Environment} StartupProduction Requires different startup UseStartup<Startup> Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { var assembly = typeof(Startup).GetTypeInfo().Assembly; webBuilder.UseStartup(assemblyName.GetName().Name); });
  • 47. Demo: Tips and tricks Convention based startup TestServer services override
  • 48. Avoid use Service Locator pattern IServiceProvider IServiceScopeFactory.CreateScope Do not directly inject HttpContext IHttpContextAccessor accessor.HttpContext.RequestServices Avoid complex lifetime graphs
  • 49. Dependency injection is integral part of .NET Core If you do not like it, replace it

Editor's Notes

  1. Alert conditions (failures and latency)
  2. https://github.com/PeterOrneholm/Orneholm.ApplicationInsights
  3. Resilient applications: tricky to choose when to intervene and when not (when degraded, should you consider it not lively, e.g.)
  4. How can restarting a container instance solve health?
  5. Evaluate log values
  6. https://www.youtube.com/watch?v=_lwCVE_XgqI https://www.youtube.com/watch?v=Zygw4UAxCdg
  7. https://medium.com/volosoft/asp-net-core-dependency-injection-best-practices-tips-tricks-c6e9c67f9d96
  8. https://github.com/aspnet/Hosting/blob/master/src/Microsoft.Extensions.Hosting/HostBuilder.cs
  9. https://github.com/aspnet/Hosting/tree/master/src/Microsoft.Extensions.Hosting
  10. https://thinkrethink.net/2018/07/12/injecting-a-scoped-service-into-ihostedservice/
  11. https://github.com/aspnet/Extensions/blob/master/src/DependencyInjection/DI/test/ServiceProviderValidationTests.cs https://andrewlock.net/new-in-asp-net-core-3-service-provider-validation/
  12. https://kristian.hellang.com/introducing-scrutor/