SlideShare ist ein Scribd-Unternehmen logo
1 von 27
Dependency Injection and
Autofac
By: Keith Schreiner & Jeff Benson
Goals
1) Provide basic info about DI.
2) Get you excited to use DI.
3) Get you to recommend using a DI tool (like
Autofac) on your next project.
Why?
DI enables loose coupling, and loose coupling makes
code more maintainable.
Great for medium or big applications that need to be
maintained.
DI can change the way you write software. (Good)
Instead of bottom-up, DI allows for top-down.
(DB to UI)

(UI to DB)
Definition of Dependency Injection
• A set of object-oriented software design principles &
patterns that enable us to develop loosely coupled
code, by passing or setting the dependencies of a
program.
• Instead of components having to request
dependencies, they are given (injected) into the
component.
• (Sounds complex, but really isn’t.)
Explain Dependency Injection to a
5-year old
When you go and get things out of the refrigerator for
yourself, you can cause problems.
You might leave the door open, you might get
something Mommy or Daddy doesn't want you to
have. You might even be looking for something we
don't even have, or which has expired.
What you should be doing is stating a need, "I need
something to drink with lunch," and then we will
make sure you have something when you sit down to
eat.
From John Munsch on Stack Overflow
DI is a set of Design Patterns &
Principles
Making code more maintainable through loose
coupling is the core motivation behind many classic
design patterns (dating back to 1995 and the Gang of Four):
Program to an interface, not an implementation
Property Injection
public partial class SomeClass
When a dependency is optional.
{
private ISomeInterface dependency;
+ Simple to understand.
public ISomeInterface Dependency
- But limited in its use.
{
get
- Not simple to implement robustly.
{
if (this.dependency == null)
this.Dependency = new DefaultSome();
return this.dependency;
}
set
{
if (value == null)
throw new ArgumentNullException("value");
if (this.dependency != null)
throw new InvalidOperationException();
this.dependency = value;
}
}
public string DoSomething(string message)
{
return this.Dependency.DoStuff(message);
}
SOLID & DI
S

Single Responsibility Principle

• An object should have only a single responsibility.
Open/Closed Principle

O

• Software entities should be open for extension, but closed for
modification.
Liskov Substitution Principle

L

• Objects in a program should be replaceable with instances of their
subtypes without altering the correctness of that program.
Interface Segregation Principle

I

• Many client specific interfaces are better than one general purpose
interface.
Dependency Inversion Principle

D

• One should depend on abstractions; do not depend upon
concretions.
Benefits of DI
•
•
•
•
•
•

Late Binding
Extensibility
Parallel Development
Maintainability
Testability
Code Structure
– Interface Driven Development
– All dependencies registered in one spot
– Never have to write code to “new-up” objects.
Negatives of DI
• Learning curve.
• Constructor code may look more complicated.

• Code may seem “magical” for developers who
do not know DI.
• Is over-kill for very small projects.
• Makes classes harder to re-use outside of a DI
app.
DI Myths
• Not just relevant for late binding.
• Not just relevant for unit testing.
• Is not just a Service Locator.
DI or Inversion of Control
Sometimes DI and IoC are interchanged.
IoC = Inversion of Control
IoC = A framework controls program flow.

IoC includes DI.
Example
A “Hello World” or any small example will do a
horrible job of showing off DI. But here it is…
[Shipping with Weather]
1.
2.
3.
4.
5.

Write some Interfaces
Implement some classes. Class Foo : IFoo
Create a class to load the modules
In this loading-class, register and configure your classes
In the startup of your program, register this loading-class
DI Dimensions (Ideas)
1) Object Composition
2) Object Interception
3) Object Lifetime Management
a)

InstancePerDependency

a)

SingleInstance

b)
c)

InstancePerLifetimeScope
InstancePerMatchingLifetimeScope
.NET DI Containers
There are many good choices (feel free to try others):
• Castle Windsor (Popular, but big. Good choice)
• Structure Map (Oldest [2004] .net DI container, popular)
• Spring.NET (port from Java, big learning curve)
• Unity (From Microsoft’s P&P team, solid but different)
• Ninject (Good, simple to use)
• Autofac (Most recent, based on C# 3, gaining popularity)
Plus about 10 other not-as-popular ones.
Autofac
• Get it: http://autofac.org or NuGet.
• What you get: a zip with binaries.
• Platforms: .NET 3.5 SP1, .NET 4, Silverlight 3 & 4, Windows
Phone 7.
• Cost? Free. It is open source.
• Help? http://autofac.org or StackOverflow
• ReSharper also really helps speed-up dev.
Autofac Integration
Autofac has additional packages for integration:
• ASP.NET WebForms
• ASP.NET MVC3
• WCF (Windows Communication Foundation)
• And others
Using Autofac
1) Develop your code using DI-friendly patterns
2) Configure Autofac
1)
2)

Create a ContainerBuilder
Add configuration.
•
Tell the ContainerBuilder your objects, and interfaces, and
lifetimes, etc.
3) Create a Container (from the ContainerBuilder)
4) Use the Container to resolve components (objects).
Configuration
• Code
• Auto (using an assembly)
• XML

Recommend: Use Package config Autofac.Module
Registering Dependencies in
Autofac
1) Type, lambda expression, specific instance, or
auto-register
builder.RegisterType<TaskController>();

builder.Register(
c => new TaskController(c.Resolve<ITaskRepository>())
);
builder.RegisterInstance(new TaskController());

builder.RegisterAssemblyTypes(typeof(IPresenter).Assembly)
.Where(t => t.IsAssignableTo<IPresenter>())
.OnActivating(e => ((IPresenter)e.Instance).SetupView());
Lifetime Options
1.
2.
3.
4.

InstancePerDependency
InstancePerLifetimeScope
InstancePerMatchingLifetimeScope
SingleInstance
Applying Autofac
• Let’s see how we can use DI and Autofac on a
big project.
• First, how one might normally create the
project without using DI.
• Second, how to create it with DI.
Common 3-tier App without DI
• Not “wrong,” but not an inherent guarantee of loose coupling
• Build Data, then BI, then UI. (bottom-up)
• The layers really are tightly coupled together, like the domain
entities from the data layer.
• Hard to test.

• Config file dependent.
Advanced Configurationg (for more
complex APIs)
Builder.RegisterType<Chicken>().As<IIngredient>();
Builder.RegisterType<Steak>().As<IIngredient>();
Last one wins, unless you ask for an array of IIngredient’s.
Builder.RegisterType<Chicken>().Named<IIngredient>(“chicken”);
Builder.RegisterType<Steak>().Named<IIngredient>(“steak”);
Can also “name” your registrations.
This allows you to do many things when working with multiple components with the same
interface, often with lambda expressions.
Builder.RegisterType<Meal>().As<IMeal>().WithParameter(
(p,c)=>true,(p,c)=>new[] {c.ResolveNamed<IIngredient>(“chicken”),
c.ResolveNamed<IIngredient>(“steak”)});
Also, if your constructor has a string, number, enum as a parameter, it is possible to register that
string as a component, or pass them in as a NamedParameter.
Summary
• Use DI to enable loose coupling and to make code
more maintainable.
• DI is just a set of good patterns, like programming to
an interface.
• Using DI can change the way you code (for the
better) because of the good patterns.
• There are several DI tools to choose from and
Autofac is good choice.
• Use DI on your next project!
Resources
• Autofac.org

• Book: “Dependency Injection in .NET” by Mark
Seemann.

http://www.manning.com/seemann/

• Podcast with Autofac creator
http://www.dotnetrocks.com/default.aspx?showNum=450

• Advanced relationship types with Autofac
http://nblumhardt.com/2010/01/the-relationship-zoo/

• Stackoverflow.com
Dependency Injection and Autofac

Weitere ähnliche Inhalte

Was ist angesagt?

Building .NET Microservices
Building .NET MicroservicesBuilding .NET Microservices
Building .NET MicroservicesVMware Tanzu
 
Java EE vs Spring Framework
Java  EE vs Spring Framework Java  EE vs Spring Framework
Java EE vs Spring Framework Rohit Kelapure
 
Mobile Application Security
Mobile Application SecurityMobile Application Security
Mobile Application Securitycclark_isec
 
Dependency injection - the right way
Dependency injection - the right wayDependency injection - the right way
Dependency injection - the right wayThibaud Desodt
 
Dependency injection and inversion
Dependency injection and inversionDependency injection and inversion
Dependency injection and inversionchhabraravish23
 
Redis Streams for Event-Driven Microservices
Redis Streams for Event-Driven MicroservicesRedis Streams for Event-Driven Microservices
Redis Streams for Event-Driven MicroservicesRedis Labs
 
#ATAGTR2019 Presentation "DevSecOps with GitLab" By Avishkar Nikale
#ATAGTR2019 Presentation "DevSecOps with GitLab" By Avishkar Nikale#ATAGTR2019 Presentation "DevSecOps with GitLab" By Avishkar Nikale
#ATAGTR2019 Presentation "DevSecOps with GitLab" By Avishkar NikaleAgile Testing Alliance
 
[DevSecOps Live] DevSecOps: Challenges and Opportunities
[DevSecOps Live] DevSecOps: Challenges and Opportunities[DevSecOps Live] DevSecOps: Challenges and Opportunities
[DevSecOps Live] DevSecOps: Challenges and OpportunitiesMohammed A. Imran
 
Let'Swift 2023 iOS 애플리케이션 개발 생산성 고찰
- 정시 퇴근을 위해 우리는 어떻게 해야할 것인가?
Let'Swift 2023 iOS 애플리케이션 개발 생산성 고찰
- 정시 퇴근을 위해 우리는 어떻게 해야할 것인가? Let'Swift 2023 iOS 애플리케이션 개발 생산성 고찰
- 정시 퇴근을 위해 우리는 어떻게 해야할 것인가?
Let'Swift 2023 iOS 애플리케이션 개발 생산성 고찰
- 정시 퇴근을 위해 우리는 어떻게 해야할 것인가? 정민 안
 
DCEU 18: Developing with Docker Containers
DCEU 18: Developing with Docker ContainersDCEU 18: Developing with Docker Containers
DCEU 18: Developing with Docker ContainersDocker, Inc.
 
DevSecOps | DevOps Sec
DevSecOps | DevOps SecDevSecOps | DevOps Sec
DevSecOps | DevOps SecRubal Jain
 
DevSecOps reference architectures 2018
DevSecOps reference architectures 2018DevSecOps reference architectures 2018
DevSecOps reference architectures 2018Sonatype
 
Platform as a Service (PaaS) - A cloud service for Developers
Platform as a Service (PaaS) - A cloud service for Developers Platform as a Service (PaaS) - A cloud service for Developers
Platform as a Service (PaaS) - A cloud service for Developers Ravindra Dastikop
 
MVVM in iOS presentation
MVVM in iOS presentationMVVM in iOS presentation
MVVM in iOS presentationG ABHISEK
 
iOS architecture patterns
iOS architecture patternsiOS architecture patterns
iOS architecture patternsallanh0526
 
CQRS: Command/Query Responsibility Segregation
CQRS: Command/Query Responsibility SegregationCQRS: Command/Query Responsibility Segregation
CQRS: Command/Query Responsibility SegregationBrian Ritchie
 

Was ist angesagt? (20)

Building .NET Microservices
Building .NET MicroservicesBuilding .NET Microservices
Building .NET Microservices
 
Java EE vs Spring Framework
Java  EE vs Spring Framework Java  EE vs Spring Framework
Java EE vs Spring Framework
 
Mobile Application Security
Mobile Application SecurityMobile Application Security
Mobile Application Security
 
Dependency injection
Dependency injectionDependency injection
Dependency injection
 
Dependency injection - the right way
Dependency injection - the right wayDependency injection - the right way
Dependency injection - the right way
 
Dependency injection and inversion
Dependency injection and inversionDependency injection and inversion
Dependency injection and inversion
 
Redis Streams for Event-Driven Microservices
Redis Streams for Event-Driven MicroservicesRedis Streams for Event-Driven Microservices
Redis Streams for Event-Driven Microservices
 
#ATAGTR2019 Presentation "DevSecOps with GitLab" By Avishkar Nikale
#ATAGTR2019 Presentation "DevSecOps with GitLab" By Avishkar Nikale#ATAGTR2019 Presentation "DevSecOps with GitLab" By Avishkar Nikale
#ATAGTR2019 Presentation "DevSecOps with GitLab" By Avishkar Nikale
 
[DevSecOps Live] DevSecOps: Challenges and Opportunities
[DevSecOps Live] DevSecOps: Challenges and Opportunities[DevSecOps Live] DevSecOps: Challenges and Opportunities
[DevSecOps Live] DevSecOps: Challenges and Opportunities
 
Let'Swift 2023 iOS 애플리케이션 개발 생산성 고찰
- 정시 퇴근을 위해 우리는 어떻게 해야할 것인가?
Let'Swift 2023 iOS 애플리케이션 개발 생산성 고찰
- 정시 퇴근을 위해 우리는 어떻게 해야할 것인가? Let'Swift 2023 iOS 애플리케이션 개발 생산성 고찰
- 정시 퇴근을 위해 우리는 어떻게 해야할 것인가?
Let'Swift 2023 iOS 애플리케이션 개발 생산성 고찰
- 정시 퇴근을 위해 우리는 어떻게 해야할 것인가?
 
DCEU 18: Developing with Docker Containers
DCEU 18: Developing with Docker ContainersDCEU 18: Developing with Docker Containers
DCEU 18: Developing with Docker Containers
 
DevSecOps 101
DevSecOps 101DevSecOps 101
DevSecOps 101
 
DevSecOps | DevOps Sec
DevSecOps | DevOps SecDevSecOps | DevOps Sec
DevSecOps | DevOps Sec
 
Dependency Inversion Principle
Dependency Inversion PrincipleDependency Inversion Principle
Dependency Inversion Principle
 
DevSecOps reference architectures 2018
DevSecOps reference architectures 2018DevSecOps reference architectures 2018
DevSecOps reference architectures 2018
 
Platform as a Service (PaaS) - A cloud service for Developers
Platform as a Service (PaaS) - A cloud service for Developers Platform as a Service (PaaS) - A cloud service for Developers
Platform as a Service (PaaS) - A cloud service for Developers
 
MVVM in iOS presentation
MVVM in iOS presentationMVVM in iOS presentation
MVVM in iOS presentation
 
iOS architecture patterns
iOS architecture patternsiOS architecture patterns
iOS architecture patterns
 
Mule with stored procedure
Mule with stored procedureMule with stored procedure
Mule with stored procedure
 
CQRS: Command/Query Responsibility Segregation
CQRS: Command/Query Responsibility SegregationCQRS: Command/Query Responsibility Segregation
CQRS: Command/Query Responsibility Segregation
 

Ähnlich wie Dependency Injection and Autofac

Cara Tepat Menjadi iOS Developer Expert - Gilang Ramadhan
Cara Tepat Menjadi iOS Developer Expert - Gilang RamadhanCara Tepat Menjadi iOS Developer Expert - Gilang Ramadhan
Cara Tepat Menjadi iOS Developer Expert - Gilang RamadhanDicodingEvent
 
Method Swizzling with Objective-C
Method Swizzling with Objective-CMethod Swizzling with Objective-C
Method Swizzling with Objective-CAdamFallon4
 
Ef Poco And Unit Testing
Ef Poco And Unit TestingEf Poco And Unit Testing
Ef Poco And Unit TestingJames Phillips
 
Design poo my_jug_en_ppt
Design poo my_jug_en_pptDesign poo my_jug_en_ppt
Design poo my_jug_en_pptagnes_crepet
 
Elements of DDD with ASP.NET MVC & Entity Framework Code First
Elements of DDD with ASP.NET MVC & Entity Framework Code FirstElements of DDD with ASP.NET MVC & Entity Framework Code First
Elements of DDD with ASP.NET MVC & Entity Framework Code FirstEnea Gabriel
 
Introduction to dependency injection in Scala (Play)
Introduction to dependency injection in Scala (Play)Introduction to dependency injection in Scala (Play)
Introduction to dependency injection in Scala (Play)Knoldus Inc.
 
OpenDaylight Developer Experience 2.0
 OpenDaylight Developer Experience 2.0 OpenDaylight Developer Experience 2.0
OpenDaylight Developer Experience 2.0Michael Vorburger
 
iOS Course day 2
iOS Course day 2iOS Course day 2
iOS Course day 2Rich Allen
 
Cut your Dependencies with Dependency Injection - .NET User Group Osnabrueck
Cut your Dependencies with Dependency Injection - .NET User Group OsnabrueckCut your Dependencies with Dependency Injection - .NET User Group Osnabrueck
Cut your Dependencies with Dependency Injection - .NET User Group OsnabrueckTheo Jungeblut
 
AEM Clean Code - Miklos Csere
AEM Clean Code - Miklos Csere AEM Clean Code - Miklos Csere
AEM Clean Code - Miklos Csere Miklos Csere
 
Clearing confusion about IoC (Inversion of Control)
Clearing confusion about IoC (Inversion of Control)Clearing confusion about IoC (Inversion of Control)
Clearing confusion about IoC (Inversion of Control)Mohammed Salah Eldowy
 
Make Cross-platform Mobile Apps Quickly - SIGGRAPH 2014
Make Cross-platform Mobile Apps Quickly - SIGGRAPH 2014Make Cross-platform Mobile Apps Quickly - SIGGRAPH 2014
Make Cross-platform Mobile Apps Quickly - SIGGRAPH 2014Gil Irizarry
 
Jump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design PatternJump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design PatternNishith Shukla
 
Jump Start To Ooad And Design Patterns
Jump Start To Ooad And Design PatternsJump Start To Ooad And Design Patterns
Jump Start To Ooad And Design PatternsLalit Kale
 
Basic iOS Training with SWIFT - Part 1
Basic iOS Training with SWIFT - Part 1Basic iOS Training with SWIFT - Part 1
Basic iOS Training with SWIFT - Part 1Manoj Ellappan
 
The Basic Concept Of IOC
The Basic Concept Of IOCThe Basic Concept Of IOC
The Basic Concept Of IOCCarl Lu
 
distage: Purely Functional Staged Dependency Injection; bonus: Faking Kind Po...
distage: Purely Functional Staged Dependency Injection; bonus: Faking Kind Po...distage: Purely Functional Staged Dependency Injection; bonus: Faking Kind Po...
distage: Purely Functional Staged Dependency Injection; bonus: Faking Kind Po...7mind
 

Ähnlich wie Dependency Injection and Autofac (20)

Cara Tepat Menjadi iOS Developer Expert - Gilang Ramadhan
Cara Tepat Menjadi iOS Developer Expert - Gilang RamadhanCara Tepat Menjadi iOS Developer Expert - Gilang Ramadhan
Cara Tepat Menjadi iOS Developer Expert - Gilang Ramadhan
 
Method Swizzling with Objective-C
Method Swizzling with Objective-CMethod Swizzling with Objective-C
Method Swizzling with Objective-C
 
Ef Poco And Unit Testing
Ef Poco And Unit TestingEf Poco And Unit Testing
Ef Poco And Unit Testing
 
Design poo my_jug_en_ppt
Design poo my_jug_en_pptDesign poo my_jug_en_ppt
Design poo my_jug_en_ppt
 
Elements of DDD with ASP.NET MVC & Entity Framework Code First
Elements of DDD with ASP.NET MVC & Entity Framework Code FirstElements of DDD with ASP.NET MVC & Entity Framework Code First
Elements of DDD with ASP.NET MVC & Entity Framework Code First
 
Introduction to dependency injection in Scala (Play)
Introduction to dependency injection in Scala (Play)Introduction to dependency injection in Scala (Play)
Introduction to dependency injection in Scala (Play)
 
Spring boot
Spring bootSpring boot
Spring boot
 
OpenDaylight Developer Experience 2.0
 OpenDaylight Developer Experience 2.0 OpenDaylight Developer Experience 2.0
OpenDaylight Developer Experience 2.0
 
iOS Course day 2
iOS Course day 2iOS Course day 2
iOS Course day 2
 
Cut your Dependencies with Dependency Injection - .NET User Group Osnabrueck
Cut your Dependencies with Dependency Injection - .NET User Group OsnabrueckCut your Dependencies with Dependency Injection - .NET User Group Osnabrueck
Cut your Dependencies with Dependency Injection - .NET User Group Osnabrueck
 
Solid OOPS
Solid OOPSSolid OOPS
Solid OOPS
 
AEM Clean Code - Miklos Csere
AEM Clean Code - Miklos Csere AEM Clean Code - Miklos Csere
AEM Clean Code - Miklos Csere
 
Clearing confusion about IoC (Inversion of Control)
Clearing confusion about IoC (Inversion of Control)Clearing confusion about IoC (Inversion of Control)
Clearing confusion about IoC (Inversion of Control)
 
Make Cross-platform Mobile Apps Quickly - SIGGRAPH 2014
Make Cross-platform Mobile Apps Quickly - SIGGRAPH 2014Make Cross-platform Mobile Apps Quickly - SIGGRAPH 2014
Make Cross-platform Mobile Apps Quickly - SIGGRAPH 2014
 
Jump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design PatternJump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design Pattern
 
Jump Start To Ooad And Design Patterns
Jump Start To Ooad And Design PatternsJump Start To Ooad And Design Patterns
Jump Start To Ooad And Design Patterns
 
Basic iOS Training with SWIFT - Part 1
Basic iOS Training with SWIFT - Part 1Basic iOS Training with SWIFT - Part 1
Basic iOS Training with SWIFT - Part 1
 
The Basic Concept Of IOC
The Basic Concept Of IOCThe Basic Concept Of IOC
The Basic Concept Of IOC
 
Android programming-basics
Android programming-basicsAndroid programming-basics
Android programming-basics
 
distage: Purely Functional Staged Dependency Injection; bonus: Faking Kind Po...
distage: Purely Functional Staged Dependency Injection; bonus: Faking Kind Po...distage: Purely Functional Staged Dependency Injection; bonus: Faking Kind Po...
distage: Purely Functional Staged Dependency Injection; bonus: Faking Kind Po...
 

Mehr von meghantaylor

Personal Time Management
Personal Time ManagementPersonal Time Management
Personal Time Managementmeghantaylor
 
Parallel Computing in .NET
Parallel Computing in .NETParallel Computing in .NET
Parallel Computing in .NETmeghantaylor
 
Best Practices for Successful Projects
Best Practices for Successful ProjectsBest Practices for Successful Projects
Best Practices for Successful Projectsmeghantaylor
 
JavaScript Framework Smackdown
JavaScript Framework SmackdownJavaScript Framework Smackdown
JavaScript Framework Smackdownmeghantaylor
 
A Software Architect's View On Diagramming
A Software Architect's View On DiagrammingA Software Architect's View On Diagramming
A Software Architect's View On Diagrammingmeghantaylor
 
Intro to Responsive Web Design
Intro to Responsive Web DesignIntro to Responsive Web Design
Intro to Responsive Web Designmeghantaylor
 

Mehr von meghantaylor (6)

Personal Time Management
Personal Time ManagementPersonal Time Management
Personal Time Management
 
Parallel Computing in .NET
Parallel Computing in .NETParallel Computing in .NET
Parallel Computing in .NET
 
Best Practices for Successful Projects
Best Practices for Successful ProjectsBest Practices for Successful Projects
Best Practices for Successful Projects
 
JavaScript Framework Smackdown
JavaScript Framework SmackdownJavaScript Framework Smackdown
JavaScript Framework Smackdown
 
A Software Architect's View On Diagramming
A Software Architect's View On DiagrammingA Software Architect's View On Diagramming
A Software Architect's View On Diagramming
 
Intro to Responsive Web Design
Intro to Responsive Web DesignIntro to Responsive Web Design
Intro to Responsive Web Design
 

Kürzlich hochgeladen

MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...Jittipong Loespradit
 
tonesoftg
tonesoftgtonesoftg
tonesoftglanshi9
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...masabamasaba
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...masabamasaba
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...masabamasaba
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park masabamasaba
 
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxAnnaArtyushina1
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...masabamasaba
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyviewmasabamasaba
 
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2
 
WSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security ProgramWSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security ProgramWSO2
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...Shane Coughlan
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Bert Jan Schrijver
 
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2
 

Kürzlich hochgeladen (20)

MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
 
WSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security ProgramWSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security Program
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 

Dependency Injection and Autofac

  • 1. Dependency Injection and Autofac By: Keith Schreiner & Jeff Benson
  • 2. Goals 1) Provide basic info about DI. 2) Get you excited to use DI. 3) Get you to recommend using a DI tool (like Autofac) on your next project.
  • 3. Why? DI enables loose coupling, and loose coupling makes code more maintainable. Great for medium or big applications that need to be maintained. DI can change the way you write software. (Good) Instead of bottom-up, DI allows for top-down. (DB to UI) (UI to DB)
  • 4. Definition of Dependency Injection • A set of object-oriented software design principles & patterns that enable us to develop loosely coupled code, by passing or setting the dependencies of a program. • Instead of components having to request dependencies, they are given (injected) into the component. • (Sounds complex, but really isn’t.)
  • 5. Explain Dependency Injection to a 5-year old When you go and get things out of the refrigerator for yourself, you can cause problems. You might leave the door open, you might get something Mommy or Daddy doesn't want you to have. You might even be looking for something we don't even have, or which has expired. What you should be doing is stating a need, "I need something to drink with lunch," and then we will make sure you have something when you sit down to eat. From John Munsch on Stack Overflow
  • 6. DI is a set of Design Patterns & Principles Making code more maintainable through loose coupling is the core motivation behind many classic design patterns (dating back to 1995 and the Gang of Four): Program to an interface, not an implementation
  • 7. Property Injection public partial class SomeClass When a dependency is optional. { private ISomeInterface dependency; + Simple to understand. public ISomeInterface Dependency - But limited in its use. { get - Not simple to implement robustly. { if (this.dependency == null) this.Dependency = new DefaultSome(); return this.dependency; } set { if (value == null) throw new ArgumentNullException("value"); if (this.dependency != null) throw new InvalidOperationException(); this.dependency = value; } } public string DoSomething(string message) { return this.Dependency.DoStuff(message); }
  • 8. SOLID & DI S Single Responsibility Principle • An object should have only a single responsibility. Open/Closed Principle O • Software entities should be open for extension, but closed for modification. Liskov Substitution Principle L • Objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program. Interface Segregation Principle I • Many client specific interfaces are better than one general purpose interface. Dependency Inversion Principle D • One should depend on abstractions; do not depend upon concretions.
  • 9. Benefits of DI • • • • • • Late Binding Extensibility Parallel Development Maintainability Testability Code Structure – Interface Driven Development – All dependencies registered in one spot – Never have to write code to “new-up” objects.
  • 10. Negatives of DI • Learning curve. • Constructor code may look more complicated. • Code may seem “magical” for developers who do not know DI. • Is over-kill for very small projects. • Makes classes harder to re-use outside of a DI app.
  • 11. DI Myths • Not just relevant for late binding. • Not just relevant for unit testing. • Is not just a Service Locator.
  • 12. DI or Inversion of Control Sometimes DI and IoC are interchanged. IoC = Inversion of Control IoC = A framework controls program flow. IoC includes DI.
  • 13. Example A “Hello World” or any small example will do a horrible job of showing off DI. But here it is… [Shipping with Weather] 1. 2. 3. 4. 5. Write some Interfaces Implement some classes. Class Foo : IFoo Create a class to load the modules In this loading-class, register and configure your classes In the startup of your program, register this loading-class
  • 14. DI Dimensions (Ideas) 1) Object Composition 2) Object Interception 3) Object Lifetime Management a) InstancePerDependency a) SingleInstance b) c) InstancePerLifetimeScope InstancePerMatchingLifetimeScope
  • 15. .NET DI Containers There are many good choices (feel free to try others): • Castle Windsor (Popular, but big. Good choice) • Structure Map (Oldest [2004] .net DI container, popular) • Spring.NET (port from Java, big learning curve) • Unity (From Microsoft’s P&P team, solid but different) • Ninject (Good, simple to use) • Autofac (Most recent, based on C# 3, gaining popularity) Plus about 10 other not-as-popular ones.
  • 16. Autofac • Get it: http://autofac.org or NuGet. • What you get: a zip with binaries. • Platforms: .NET 3.5 SP1, .NET 4, Silverlight 3 & 4, Windows Phone 7. • Cost? Free. It is open source. • Help? http://autofac.org or StackOverflow • ReSharper also really helps speed-up dev.
  • 17. Autofac Integration Autofac has additional packages for integration: • ASP.NET WebForms • ASP.NET MVC3 • WCF (Windows Communication Foundation) • And others
  • 18. Using Autofac 1) Develop your code using DI-friendly patterns 2) Configure Autofac 1) 2) Create a ContainerBuilder Add configuration. • Tell the ContainerBuilder your objects, and interfaces, and lifetimes, etc. 3) Create a Container (from the ContainerBuilder) 4) Use the Container to resolve components (objects).
  • 19. Configuration • Code • Auto (using an assembly) • XML Recommend: Use Package config Autofac.Module
  • 20. Registering Dependencies in Autofac 1) Type, lambda expression, specific instance, or auto-register builder.RegisterType<TaskController>(); builder.Register( c => new TaskController(c.Resolve<ITaskRepository>()) ); builder.RegisterInstance(new TaskController()); builder.RegisterAssemblyTypes(typeof(IPresenter).Assembly) .Where(t => t.IsAssignableTo<IPresenter>()) .OnActivating(e => ((IPresenter)e.Instance).SetupView());
  • 22. Applying Autofac • Let’s see how we can use DI and Autofac on a big project. • First, how one might normally create the project without using DI. • Second, how to create it with DI.
  • 23. Common 3-tier App without DI • Not “wrong,” but not an inherent guarantee of loose coupling • Build Data, then BI, then UI. (bottom-up) • The layers really are tightly coupled together, like the domain entities from the data layer. • Hard to test. • Config file dependent.
  • 24. Advanced Configurationg (for more complex APIs) Builder.RegisterType<Chicken>().As<IIngredient>(); Builder.RegisterType<Steak>().As<IIngredient>(); Last one wins, unless you ask for an array of IIngredient’s. Builder.RegisterType<Chicken>().Named<IIngredient>(“chicken”); Builder.RegisterType<Steak>().Named<IIngredient>(“steak”); Can also “name” your registrations. This allows you to do many things when working with multiple components with the same interface, often with lambda expressions. Builder.RegisterType<Meal>().As<IMeal>().WithParameter( (p,c)=>true,(p,c)=>new[] {c.ResolveNamed<IIngredient>(“chicken”), c.ResolveNamed<IIngredient>(“steak”)}); Also, if your constructor has a string, number, enum as a parameter, it is possible to register that string as a component, or pass them in as a NamedParameter.
  • 25. Summary • Use DI to enable loose coupling and to make code more maintainable. • DI is just a set of good patterns, like programming to an interface. • Using DI can change the way you code (for the better) because of the good patterns. • There are several DI tools to choose from and Autofac is good choice. • Use DI on your next project!
  • 26. Resources • Autofac.org • Book: “Dependency Injection in .NET” by Mark Seemann. http://www.manning.com/seemann/ • Podcast with Autofac creator http://www.dotnetrocks.com/default.aspx?showNum=450 • Advanced relationship types with Autofac http://nblumhardt.com/2010/01/the-relationship-zoo/ • Stackoverflow.com

Hinweis der Redaktion

  1. Keith does “Overview”Jeff dos “Goals”
  2. Jeff
  3. Jeff
  4. Jeff does the rest of these slides.