SlideShare uma empresa Scribd logo
1 de 24
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
Controllerconstructors
@inject
FromServicesAttribute
Application-andRequestServices
Hosting outside
and without ASP.NET Core
IHostedService
BackgroundService
Uses new Host, and
IHostBuilder for hosting
WebHostBuilder
HostBuilder Configure
Startup
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
Demo code:
https://github.com/alexthissen/DependencyInjection
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

Mais conteúdo relacionado

Mais procurados

Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!
Jakub Kubrynski
 

Mais procurados (20)

Collections and its types in C# (with examples)
Collections and its types in C# (with examples)Collections and its types in C# (with examples)
Collections and its types in C# (with examples)
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Spring boot introduction
Spring boot introductionSpring boot introduction
Spring boot introduction
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API
 
Spring boot
Spring bootSpring boot
Spring boot
 
ASP.NET Web API and HTTP Fundamentals
ASP.NET Web API and HTTP FundamentalsASP.NET Web API and HTTP Fundamentals
ASP.NET Web API and HTTP Fundamentals
 
Dependency injection - the right way
Dependency injection - the right wayDependency injection - the right way
Dependency injection - the right way
 
JPA For Beginner's
JPA For Beginner'sJPA For Beginner's
JPA For Beginner's
 
An Introduction To REST API
An Introduction To REST APIAn Introduction To REST API
An Introduction To REST API
 
Introduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoCIntroduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoC
 
Spring Framework
Spring FrameworkSpring Framework
Spring Framework
 
Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans
 
ASP.NET Core MVC + Web API with Overview
ASP.NET Core MVC + Web API with OverviewASP.NET Core MVC + Web API with Overview
ASP.NET Core MVC + Web API with Overview
 
Web api
Web apiWeb api
Web api
 
Exception handling in asp.net
Exception handling in asp.netException handling in asp.net
Exception handling in asp.net
 
Asp.Net Core MVC , Razor page , Entity Framework Core
Asp.Net Core MVC , Razor page , Entity Framework CoreAsp.Net Core MVC , Razor page , Entity Framework Core
Asp.Net Core MVC , Razor page , Entity Framework Core
 
Spring Boot in Action
Spring Boot in Action Spring Boot in Action
Spring Boot in Action
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!
 

Semelhante a It depends: Loving .NET Core dependency injection or not

Semelhante a It depends: Loving .NET Core dependency injection or not (20)

Tdd,Ioc
Tdd,IocTdd,Ioc
Tdd,Ioc
 
2016 07 - CloudBridge Python library (XSEDE16)
2016 07 - CloudBridge Python library (XSEDE16)2016 07 - CloudBridge Python library (XSEDE16)
2016 07 - CloudBridge Python library (XSEDE16)
 
Alex Thissen "It depends: loving .NET Core dependency injection or not"
Alex Thissen "It depends: loving .NET Core dependency injection or not"Alex Thissen "It depends: loving .NET Core dependency injection or not"
Alex Thissen "It depends: loving .NET Core dependency injection or not"
 
“ASP.NET Core. Features and architecture”
“ASP.NET Core. Features and architecture” “ASP.NET Core. Features and architecture”
“ASP.NET Core. Features and architecture”
 
.NET Core, ASP.NET Core Course, Session 17
.NET Core, ASP.NET Core Course, Session 17.NET Core, ASP.NET Core Course, Session 17
.NET Core, ASP.NET Core Course, Session 17
 
.NET Core: a new .NET Platform
.NET Core: a new .NET Platform.NET Core: a new .NET Platform
.NET Core: a new .NET Platform
 
Real World Asp.Net WebApi Applications
Real World Asp.Net WebApi ApplicationsReal World Asp.Net WebApi Applications
Real World Asp.Net WebApi Applications
 
Constructor injection and other new features for Declarative Services 1.4
Constructor injection and other new features for Declarative Services 1.4Constructor injection and other new features for Declarative Services 1.4
Constructor injection and other new features for Declarative Services 1.4
 
Field injection, type safe configuration, and more new goodies in Declarative...
Field injection, type safe configuration, and more new goodies in Declarative...Field injection, type safe configuration, and more new goodies in Declarative...
Field injection, type safe configuration, and more new goodies in Declarative...
 
.NET Core, ASP.NET Core Course, Session 6
.NET Core, ASP.NET Core Course, Session 6.NET Core, ASP.NET Core Course, Session 6
.NET Core, ASP.NET Core Course, Session 6
 
Divide and Conquer – Microservices with Node.js
Divide and Conquer – Microservices with Node.jsDivide and Conquer – Microservices with Node.js
Divide and Conquer – Microservices with Node.js
 
Continuous Integration e Delivery per (r)innovare lo sviluppo software e la g...
Continuous Integration e Delivery per (r)innovare lo sviluppo software e la g...Continuous Integration e Delivery per (r)innovare lo sviluppo software e la g...
Continuous Integration e Delivery per (r)innovare lo sviluppo software e la g...
 
.NET Core Apps: Design & Development
.NET Core Apps: Design & Development.NET Core Apps: Design & Development
.NET Core Apps: Design & Development
 
Azure serverless architectures
Azure serverless architecturesAzure serverless architectures
Azure serverless architectures
 
Struts 2 - Introduction
Struts 2 - Introduction Struts 2 - Introduction
Struts 2 - Introduction
 
ASP.NET Core 1.0
ASP.NET Core 1.0ASP.NET Core 1.0
ASP.NET Core 1.0
 
AWS Lambda in C#
AWS Lambda in C#AWS Lambda in C#
AWS Lambda in C#
 
Building strong foundations apex enterprise patterns
Building strong foundations apex enterprise patternsBuilding strong foundations apex enterprise patterns
Building strong foundations apex enterprise patterns
 
ACDKOCHI19 - CI / CD using AWS Developer Tools
ACDKOCHI19 - CI / CD using AWS Developer ToolsACDKOCHI19 - CI / CD using AWS Developer Tools
ACDKOCHI19 - CI / CD using AWS Developer Tools
 
DDD, CQRS and testing with ASP.Net MVC
DDD, CQRS and testing with ASP.Net MVCDDD, CQRS and testing with ASP.Net MVC
DDD, CQRS and testing with ASP.Net MVC
 

Mais de Alex Thissen

Health monitoring and dependency injection - CNUG November 2019
Health monitoring and dependency injection - CNUG November 2019Health monitoring and dependency injection - CNUG November 2019
Health monitoring and dependency injection - CNUG November 2019
Alex Thissen
 

Mais de 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
 
Health monitoring and dependency injection - CNUG November 2019
Health monitoring and dependency injection - CNUG November 2019Health monitoring and dependency injection - CNUG November 2019
Health monitoring and dependency injection - CNUG November 2019
 
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
 
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 - ...
 
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!
 

Último

No Advance 8868886958 Chandigarh Call Girls , Indian Call Girls For Full Nigh...
No Advance 8868886958 Chandigarh Call Girls , Indian Call Girls For Full Nigh...No Advance 8868886958 Chandigarh Call Girls , Indian Call Girls For Full Nigh...
No Advance 8868886958 Chandigarh Call Girls , Indian Call Girls For Full Nigh...
Sheetaleventcompany
 
If this Giant Must Walk: A Manifesto for a New Nigeria
If this Giant Must Walk: A Manifesto for a New NigeriaIf this Giant Must Walk: A Manifesto for a New Nigeria
If this Giant Must Walk: A Manifesto for a New Nigeria
Kayode Fayemi
 
Chiulli_Aurora_Oman_Raffaele_Beowulf.pptx
Chiulli_Aurora_Oman_Raffaele_Beowulf.pptxChiulli_Aurora_Oman_Raffaele_Beowulf.pptx
Chiulli_Aurora_Oman_Raffaele_Beowulf.pptx
raffaeleoman
 

Último (20)

VVIP Call Girls Nalasopara : 9892124323, Call Girls in Nalasopara Services
VVIP Call Girls Nalasopara : 9892124323, Call Girls in Nalasopara ServicesVVIP Call Girls Nalasopara : 9892124323, Call Girls in Nalasopara Services
VVIP Call Girls Nalasopara : 9892124323, Call Girls in Nalasopara Services
 
ANCHORING SCRIPT FOR A CULTURAL EVENT.docx
ANCHORING SCRIPT FOR A CULTURAL EVENT.docxANCHORING SCRIPT FOR A CULTURAL EVENT.docx
ANCHORING SCRIPT FOR A CULTURAL EVENT.docx
 
ICT role in 21st century education and it's challenges.pdf
ICT role in 21st century education and it's challenges.pdfICT role in 21st century education and it's challenges.pdf
ICT role in 21st century education and it's challenges.pdf
 
No Advance 8868886958 Chandigarh Call Girls , Indian Call Girls For Full Nigh...
No Advance 8868886958 Chandigarh Call Girls , Indian Call Girls For Full Nigh...No Advance 8868886958 Chandigarh Call Girls , Indian Call Girls For Full Nigh...
No Advance 8868886958 Chandigarh Call Girls , Indian Call Girls For Full Nigh...
 
Causes of poverty in France presentation.pptx
Causes of poverty in France presentation.pptxCauses of poverty in France presentation.pptx
Causes of poverty in France presentation.pptx
 
If this Giant Must Walk: A Manifesto for a New Nigeria
If this Giant Must Walk: A Manifesto for a New NigeriaIf this Giant Must Walk: A Manifesto for a New Nigeria
If this Giant Must Walk: A Manifesto for a New Nigeria
 
Introduction to Prompt Engineering (Focusing on ChatGPT)
Introduction to Prompt Engineering (Focusing on ChatGPT)Introduction to Prompt Engineering (Focusing on ChatGPT)
Introduction to Prompt Engineering (Focusing on ChatGPT)
 
Air breathing and respiratory adaptations in diver animals
Air breathing and respiratory adaptations in diver animalsAir breathing and respiratory adaptations in diver animals
Air breathing and respiratory adaptations in diver animals
 
Dreaming Music Video Treatment _ Project & Portfolio III
Dreaming Music Video Treatment _ Project & Portfolio IIIDreaming Music Video Treatment _ Project & Portfolio III
Dreaming Music Video Treatment _ Project & Portfolio III
 
Dreaming Marissa Sánchez Music Video Treatment
Dreaming Marissa Sánchez Music Video TreatmentDreaming Marissa Sánchez Music Video Treatment
Dreaming Marissa Sánchez Music Video Treatment
 
Re-membering the Bard: Revisiting The Compleat Wrks of Wllm Shkspr (Abridged)...
Re-membering the Bard: Revisiting The Compleat Wrks of Wllm Shkspr (Abridged)...Re-membering the Bard: Revisiting The Compleat Wrks of Wllm Shkspr (Abridged)...
Re-membering the Bard: Revisiting The Compleat Wrks of Wllm Shkspr (Abridged)...
 
Chiulli_Aurora_Oman_Raffaele_Beowulf.pptx
Chiulli_Aurora_Oman_Raffaele_Beowulf.pptxChiulli_Aurora_Oman_Raffaele_Beowulf.pptx
Chiulli_Aurora_Oman_Raffaele_Beowulf.pptx
 
Call Girl Number in Khar Mumbai📲 9892124323 💞 Full Night Enjoy
Call Girl Number in Khar Mumbai📲 9892124323 💞 Full Night EnjoyCall Girl Number in Khar Mumbai📲 9892124323 💞 Full Night Enjoy
Call Girl Number in Khar Mumbai📲 9892124323 💞 Full Night Enjoy
 
Busty Desi⚡Call Girls in Sector 51 Noida Escorts >༒8448380779 Escort Service-...
Busty Desi⚡Call Girls in Sector 51 Noida Escorts >༒8448380779 Escort Service-...Busty Desi⚡Call Girls in Sector 51 Noida Escorts >༒8448380779 Escort Service-...
Busty Desi⚡Call Girls in Sector 51 Noida Escorts >༒8448380779 Escort Service-...
 
SaaStr Workshop Wednesday w/ Lucas Price, Yardstick
SaaStr Workshop Wednesday w/ Lucas Price, YardstickSaaStr Workshop Wednesday w/ Lucas Price, Yardstick
SaaStr Workshop Wednesday w/ Lucas Price, Yardstick
 
My Presentation "In Your Hands" by Halle Bailey
My Presentation "In Your Hands" by Halle BaileyMy Presentation "In Your Hands" by Halle Bailey
My Presentation "In Your Hands" by Halle Bailey
 
Presentation on Engagement in Book Clubs
Presentation on Engagement in Book ClubsPresentation on Engagement in Book Clubs
Presentation on Engagement in Book Clubs
 
BDSM⚡Call Girls in Sector 97 Noida Escorts >༒8448380779 Escort Service
BDSM⚡Call Girls in Sector 97 Noida Escorts >༒8448380779 Escort ServiceBDSM⚡Call Girls in Sector 97 Noida Escorts >༒8448380779 Escort Service
BDSM⚡Call Girls in Sector 97 Noida Escorts >༒8448380779 Escort Service
 
Mohammad_Alnahdi_Oral_Presentation_Assignment.pptx
Mohammad_Alnahdi_Oral_Presentation_Assignment.pptxMohammad_Alnahdi_Oral_Presentation_Assignment.pptx
Mohammad_Alnahdi_Oral_Presentation_Assignment.pptx
 
Report Writing Webinar Training
Report Writing Webinar TrainingReport Writing Webinar Training
Report Writing Webinar Training
 

It depends: Loving .NET Core dependency injection or not

Notas do Editor

  1. https://www.youtube.com/watch?v=_lwCVE_XgqI https://www.youtube.com/watch?v=Zygw4UAxCdg
  2. https://medium.com/volosoft/asp-net-core-dependency-injection-best-practices-tips-tricks-c6e9c67f9d96
  3. https://github.com/aspnet/Hosting/blob/master/src/Microsoft.Extensions.Hosting/HostBuilder.cs
  4. https://github.com/aspnet/Hosting/tree/master/src/Microsoft.Extensions.Hosting
  5. https://thinkrethink.net/2018/07/12/injecting-a-scoped-service-into-ihostedservice/
  6. 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/
  7. https://kristian.hellang.com/introducing-scrutor/