36
Comparing Inversion-Of-Control Containers Comparison of .Net IoC Containers

Comparing Inversion-Of-Control Containers

  • Upload
    tuyen

  • View
    42

  • Download
    0

Embed Size (px)

DESCRIPTION

Comparing Inversion-Of-Control Containers. Comparison of .Net IoC Containers. Have Your Mind Blown!. http://codestock.org. August 9, 2008 Knoxville, TN. Devlink Technical Conference. http://devlink.net. August 22 - 23, 2008 Murfreesboro, TN. Who is Chris Rauber ?. - PowerPoint PPT Presentation

Citation preview

Inversion of control

Comparing Inversion-Of-Control ContainersComparison of .Net IoC ContainersHave Your Mind Blown!August 9, 2008 Knoxville, TNhttp://codestock.org

Devlink Technical ConferenceAugust 22 - 23, 2008 Murfreesboro, TNhttp://devlink.net

Who is Chris Rauber?A senior software developer and application architect with over 10 years experience designing, developing, building, and testing software applicationsHe has worked with clients ranging from Fortune 500 companies to five-persons IT shops A polyglot programmer, with expertise in C#, Java, VB.Net, JavaScript, and Ruby. The founder and author of Miado, an open-source data-access layer witten in C# that simplifies the use of ADO.Net. Chris earned his Bachelor of Science in Industrial & Labor Relations from Cornell University in 1995 and his Master of Science in Computer Information Systems from Georgia State University in 1999.

Who is Alan Stevens?An Independent Web DeveloperPresidentEast Tennessee .NET Users Grouphttp://etnug.orgOccasional Blogger http://netcave.orgASP Insiderhttp://aspinsiders.comAn Enthusiast NOT an expert!A member of the elite Kung Fu Geeks

As Seen On TwitterInversion of Control is the scar tissue of J2EE ContainersJeremy MillerCreator of StructureMap

HistoryGang of Four Design Patterns (1994)In the discussion of the Template Method pattern:

Template methods lead to an inverted control structure thats sometimes referred to as The Hollywood Principle, that is, Dont call us, well call you. Inversion Of ControlDefinitionThe flow of control in a component is not controlled by the component itself, but rather by some outside entity

In other wordsObjects should not be responsible for creating and managing their own dependenciesDependency InjectionA specific form of Inversion Of Control

An objects dependencies are created by some external entity and injected into it

Separation Of ConcernsBreak our applications into distinct modules that dont overlap in responsibilitiesExamples:MVCUI, Service, DALHTML, CSSThe goal is code that is highly cohesive with low coupling

CohesionThe degree to which the responsibilities within a given class are strongly related

Highly cohesive code is:More readable and easier to understandEasier to manage, maintain, and testLikely to be reusedReduced complexity

Code With Low Cohesionprotected void btnSubmit_click(object sender, EventArgs e){ if ( !this.IsValid(this.txtUserName.Text, this.txtPassword.Text) ) {}}

private bool IsValid(string userName, string password){ bool isValid = false; using ( SqlConnection conn = new SqlConnection(_connString) ) { using ( SqlCommand cmd = conn.CreateCommand() ) { // query on User Name and Password isValid = cmd.ExecuteScalar(); } } return isValid;}CouplingThe degree to which a given concrete class is dependent on another concrete class

Reducing coupling provides:More flexibilityEase of swapping implementations Ability to refactorComponents that are more testable

Highly Coupled Codepublic void ResetPassword(User user) { user.Password = PasswordGenerator.GenerateNewPassword();

MailMessage email = new MailMessage( "[email protected]", user.Email, "Password Reset", String.Format("Your password has been reset to: {0}", user.Password)); SmtpClient smtp = new SmtpClient(); smtp.Send(email); EventLog.WriteEntry( "LoginService", String.Format("Reset password for {0}", user.UserName), EventLogEntryType.Information);}SOLID PrinciplesSingle Responsibility PrincipleOpen Closed PrincipleLiskov Substitution PrincipleInterface Segregation PrincipleDependency Inversion PrincipleSRP The Single Responsibility Principle A class should have one, and only one, reason to change.OCP The Open Closed Principle You should be able to extend a classes behavior, without modifying it.LSP The Liskov Substitution Principle Derived classes must be substitutable for their base classes.ISP The Interface Segregation Principle Clients should not be forced to depend on interfaces that they do not use.DIP The Dependency Inversion Principle Depend on abstractions, not on concretions.16The Single Responsibility Principle A class should have one, and only one, reason to change.The Open Closed PrincipleYou should be able to extend a classes behavior, without modifying it.The Liskov Substitution Principle Derived classes must be substitutable for their base classes.The Interface Segregation Principle Clients should not be forced to depend on interfaces that they do not use.The Dependency Inversion Principle Depend on abstractions, not on concretions.

*ILITIESAgilityTestabilityReversibilityChangeabilityFlexibilityMaintainabilityTestabilityTests become very granularTests can focus on a classs single responsibility, and inject mock dependenciesTestability is a good barometer of couplingHighly cohesive, low coupled code is much easier to testAgilityDependency injection frees us to change implementations without affecting calling codeModules become easy to refactorHighly flexible softwareContainer?A container is nothing more than a fancy dictionary of interfaces and their implementing typesInversion Of Control containers act like super factories

Auto wiringAutomatically resolve inter-class dependenciesObjects are pre-populated with all their dependencies when retrieved from the containerSignificantly reduces the amount of code needed to resolve dependencies

Lifecycle ManagementSingletons are evil!IoC containers can control instance behaviorClient code is shielded from the lifecycle decisions of its dependencies Spring FrameworkRod Johnson, founder and creatorExpert One-on-One J2EE Design and Development (2002)Our business code had become polluted with J2EE container dependenciesWriting testable J2EE apps in a traditional manner was hardSetter injection allowed us to isolate and inject container dependencies Dependency injection led to interfaces that were easy to mockUnity (Microsoft)AdvantagesMicrosoftSimple, straight-forward configuration APIMethod chaining when initializing

DisadvantagesMicrosoftEnterprise Library hangoverLimited feature setNew framework on the blockWindsor (Castle Project)AdvantagesProbably the most widely used Full featured and well documentedVery active communityNative support for AOPMore choices for lifecycle managementBuilt-in support for Logging and TransactionsPlays well with other open-source tools

DisadvantagesStill only in Release Candidate stageNinjectAdvantagesVery FastFull featured and well documentedVery active developmentNo need for XML configuration filesHighly extensibleDisadvantagesDefault use of attributesNew, version 1.0

StructureMapAdvantagesMature code baseFlexible configuration optionsDeveloped by Jeremy D. MillerDisadvantagesFlexibility leads to complexityDocumentation is lacking

DEMODrawbacks of IoCArchitecture is less straight-forwardOverkill for smaller or throwaway applicationsEasy to abuseBe careful to avoid XML Hell in configuration filesResourceshttp://www.martinfowler.com/articles/injection.htmlhttp://www.codeplex.com/unity/http://www.castleproject.org/container/http://www.ninject.orghttp://structuremap.sourceforge.nethttp://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOodhttp://msdn2.microsoft.com/en-us/magazine/cc337885.aspx

Thanks For Listening!Email/IM: [email protected]@gmail.com

Blog: http://netcave.orghttp://www.chrisrauber.com/blog/

Twitter: @alanstevens@chrisrauber