asp.net core dependency injection & unit testing

12
ASP.NET Core Dependency Injection & Unit Testing Robert Haken software architect, HAVIT, s.r.o. [email protected], @RobertHaken Microsoft MVP: Development, MCT, MCSD

Upload: others

Post on 15-Jul-2022

16 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: ASP.NET Core Dependency Injection & Unit Testing

ASP.NET CoreDependency Injection& Unit Testing

Robert Hakensoftware architect, HAVIT, [email protected], @RobertHakenMicrosoft MVP: Development, MCT, MCSD

Page 2: ASP.NET Core Dependency Injection & Unit Testing

OCHUTNÁVKA

ASP.NET Core - MVC6 ControllerIEmailSender Dependency Injection demo

Page 3: ASP.NET Core Dependency Injection & Unit Testing

DependencyInjection

"Dependency Injection is a set of software design principles and patternsthat enable us to develop loosely coupled code."

Mark Seeman

Page 4: ASP.NET Core Dependency Injection & Unit Testing

DependencyInjectionBenefits

loosely coupled code=>

• Late-binding

• Extensibility

• ParallelDevelopment

• Maintainability

• Testability

Page 5: ASP.NET Core Dependency Injection & Unit Testing

DEMO

Price Resolver - Dependency Injection, Unit-Testing

Page 6: ASP.NET Core Dependency Injection & Unit Testing

"Good" Unit Test

• automated+ repeatable

• fully isolated

• consistent in itsresults

• runsquickly

• full control of the unit under test(alldependencies)

• relevanttomorrow

• easyto implement

• able to run it at the push of a button

• iffails=> easy to detect what was expected

Page 7: ASP.NET Core Dependency Injection & Unit Testing

DependencyInjectionContainers

• ObjectComposition

• ObjectLifetime

• Interception

• Code-based/ XML-basedconfiguration

– Auto-wiring, convention-basedconfiguration, ...

Page 8: ASP.NET Core Dependency Injection & Unit Testing

ASP.NET CoreDI "Container" -Register

• Startup.cs– Configure[Env]Services(IServiceCollection services)

• API -Lifestyles– services.AddTransient<TAbstraction, TImplementation>()

– services.AddScoped<TAbstraction, TImplementation>()

– services.AddSingleton<TAbstraction, TImplementation>()

– services.AddSingleton<TAbstraction>(instance)

– plus factory-methodverze

Page 9: ASP.NET Core Dependency Injection & Unit Testing

DEMO

ASP.NET Core DI - LifeStyles

Page 10: ASP.NET Core Dependency Injection & Unit Testing

ASP.NET CoreDI "Container" - Injection

Controllers

– constructorinjection

– Action-methodinjection[FromServices]

Views

– propertyinjection @inject TService PropertyName

Models

– propertyinjection [FromServices]

Startup: Configure()

– methodinjection

Page 11: ASP.NET Core Dependency Injection & Unit Testing

ASP.NET CoreDI "Container" - InjectionII.

Middleware

– constructorinjection

– methodinjectionInvoke(...)

Filters

– "attribute" injection[ServiceFilter(typeof(...))]

– "attribute" injection[TypeFilter(typeof(...))]

Other

– constructorinjection

Page 12: ASP.NET Core Dependency Injection & Unit Testing

Q & A