Dependency Injection Autofac is an addictive Inversion of

  • Slides: 10
Download presentation
Dependency Injection Autofac is an addictive Inversion of Control container for. NET Core, ASP.

Dependency Injection Autofac is an addictive Inversion of Control container for. NET Core, ASP. NET Core, . NET 4. 5. 1+, Universal Windows apps, and more.

What is it trying to solve? Problem Statement • • Tight Coupling Cannot isolate

What is it trying to solve? Problem Statement • • Tight Coupling Cannot isolate Unit Test Cannot mock TCPClient Harder to find bugs when test fails Tests take longer time to complete Blackbox Dependency! Is it doing too many things? Private functions can’t be tested

Solution #1 – Factory Pattern • A single class, or a group of classes

Solution #1 – Factory Pattern • A single class, or a group of classes dedicated to create dependencies on behalf of others

Solution #1 – Factory Pattern • Tight Coupling reduced! But still exists • SOLID

Solution #1 – Factory Pattern • Tight Coupling reduced! But still exists • SOLID D Dependency Inversion Principle states that • High level modules should not depend upon low level modules. Both should depend upon abstractions. • Test. Class still depending on concrete implementation of TCPClient. We need to fix a contract via a Interface • Cannot isolate Unit Test • Cannot mock TCPClient • Harder to find bugs when test fails • Tests take longer time to complete • Blackbox Dependency!

Solution #1 – Factory Pattern • • • Loose Coupling Cannot isolate Unit Test

Solution #1 – Factory Pattern • • • Loose Coupling Cannot isolate Unit Test Cannot mock TCPClient Harder to find bugs when test fails Tests take longer time to complete Blackbox Dependency!

Solution #1 – Factory Pattern Inject Dependencies through Constructor • No Coupling • Unit

Solution #1 – Factory Pattern Inject Dependencies through Constructor • No Coupling • Unit Test can be performed in isolation as dependencies can now be mocked • Everyone reading the API knows what dependencies are needed to be injected and used by the class

Solution #1 – Factory Pattern Inject Dependencies through Constructor • Somewhere in the application,

Solution #1 – Factory Pattern Inject Dependencies through Constructor • Somewhere in the application, injection is manually done by using the Factory classes • But this can get real messy when a dependency itself requires other dependencies

Solution #1 – Factory Pattern Inject Dependencies through Constructor • Class. Factory can get

Solution #1 – Factory Pattern Inject Dependencies through Constructor • Class. Factory can get messy

Solution #2 – Auto. Fac • Register once, Use everywhere

Solution #2 – Auto. Fac • Register once, Use everywhere

Solution #2 – Auto. Fac • • Test. Class needs A, B and C

Solution #2 – Auto. Fac • • Test. Class needs A, B and C A needs A 1 and A 2 Auto. Fac creates A Auto. Fac creates B Auto. Fac creates C Auto. Fac creats Test. Class