Onion Architecture with S#arp
Upcoming SlideShare
Loading in...5
×

Like this? Share it with your network

Share

Onion Architecture with S#arp

  • 3,052 views
Uploaded on

As presented to the Milwaukee Alt.Net group on November 21st, 2011. ...

As presented to the Milwaukee Alt.Net group on November 21st, 2011.

UPDATE April 19, 2012: added some domain logic organization slides using Fowler's 4 basic patterns.

More in: Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads

Views

Total Views
3,052
On Slideshare
3,048
From Embeds
4
Number of Embeds
3

Actions

Shares
Downloads
33
Comments
0
Likes
2

Embeds 4

http://speakerrate.com 2
http://a0.twimg.com 1
http://twitter.com 1

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide
  • http://www.amazon.com/Patterns-Enterprise-Application-Architecture-Martin/dp/0321127420/ref=sr_1_1?ie=UTF8&qid=1334844499&sr=8-14 Domain Logic patterns - Transaction Script (110), Domain Model (116), Table Module (125), Service Layer (133).Some cross-over with Data Source Architectural Patterns
  • Fowler calls Active Record a Data Source Architectural Pattern, not a Domain Logic Pattern
  • Service – the most overloaded term in softwareNote that we’re not suggesting distribution here, so all of this could be in process - Distribution Patterns:Remote Facade (388), Data Transfer Object (401)
  • The rise of things like automappers seems to suggest that everyone is reaching agreement that MVx models != domain models, and these are only presentation patternsFowler calls this a presentation pattern
  • Fowler calls this a Data Source Architectural Pattern
  • Implicit here is that the domain logic, the business logic, the behavior specific to the task at hand is where the competitive advantage is, and infrastructure-type code is commodity, boiler plate
  • Picture: Meet a Meaningless Metaphor, http://wakefelderman.blogspot.com
  • The Onion Architecture is a great metaphor to help us grasp how these concepts work within a real application.

Transcript

  • 1. Implementing theOnion Architecture Gary Pedretti – Gary.Pedretti@Centare.com 4/19/2012 Logo, Design, and Company Information:© 2011 Centare Group, Ltd. Slide Show and Notes Content: Creative Commons License, Gary Pedretti Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.
  • 2. About Centare Consulting Services Organization Primary focus on Agile, Mobile and Cloud Individual and team based development .NET, Java, and iOS technology stacks Microsoft Gold Partner in ALM Training, coaching, mentoring & team building Full Scrum.org course offering Best practices training Technical and business leadership strategies
  • 3. Gary PedrettiSolutions Manager, Agile PracticeOver 12 years in the software industry – DBA, Developer,BA, Application ArchitectScrum: Team member, Scrum Master, Coach, CertifiedScrum Trainer for Scrum.orghttp://blog.GaryPedretti.com/@GaryPedrettihttp://www.linkedin.com/in/garypedrettiMCPD 4.0 Web, MCTS 4.0 WCF/Web/Data Access, MCDBA MSSQL 2000, PSM, PSD .NET, PSD Java, CSM, MCPD 3.5 ASP.NET,MCTS 3.5 WCF/ASP.NET/ADO.NET, MCTS SharePoint 2003 Infrastructure, MCPD 2.0 Enterprise, MCTS 2.0 Distributed/Web/Windows,MCSD 1.1, MCAD 1.1, MOUS
  • 4. Onion Architecture S#arp Implementing the Onion Architecture with S#arp Custom Code
  • 5. Let’s Talk Business Logic….DomainLogic…Behavior…
  • 6. Fowler and “The Bible”Four Domain LogicPatterns
  • 7. 1. Transaction Script – “Anemic Domain” Organizes business logic by procedures where each procedure handles a single request from the presentation. Little different from the Procedural paradigm Is this Object-Oriented?
  • 8. 2. Table Module – Object Model ~= Data Model A single instance that handles the business logic for all rows in a database table or view. Think DataSet – if you built behavior around it Differs from Active Record because it holds all rows, not a single row
  • 9. 3. Service Layer Defines an applications boundary with a layer of services that establishes a set of available operations and coordinates the applications response in each operation “Service” - arrrrrggggggghhhhhhhhhh
  • 10. 4. Domain Model An object model of the domain that incorporates both behavior and data. This is just Object Orientation!!!! That’s it!!! This is also Domain Driven Design…kinda
  • 11. Other Patterns Where do these fit in? Presentation patterns Data Source patterns
  • 12. Model View Controller…or MVx Splits user interface interaction into three distinct roles. Is this presentation only?
  • 13. Active Record An object that wraps a row in a database table or view, encapsulates the database access, and adds domain logic on that data. Isn’t this at the same level as a Table Module? Still Object Model ~= Data Model
  • 14. Let’s Talk Layers…and Tiers
  • 15. Traditional Layered ArchitectureImages:http://jeffreypalermo.com
  • 16. Traditional Layered Architecture – AnemicDomain?
  • 17. Image: http://jeffreypalermo.com
  • 18. Key Tenets of Onion Architecture The application is built around an independent object model Inner layers define interfaces. Outer layers implement interfaces Direction of coupling is toward the center All application core code can be compiled and run separate from infrastructureSource: http://jeffreypalermo.com/blog/the-onion-architecture-part-3/
  • 19. AKA “Ports and Adapters” or “Object Structural” or “Hexagonal Architecture”Image: http://alistair.cockburn.us/Hexagonal+architecture
  • 20. AKA “Ports and Adapters” or “ObjectStructural” or “Hexagonal Architecture” Create your application to work without either a UI or a database so you can Run automated regression-tests against the application Work when the database becomes unavailable Link applications together without any user involvement- Alistair Cockburn, http://alistair.cockburn.us/Hexagonal+architecture
  • 21. If we were to represent the OnionArchitecture flattened…Image: http://jeffreypalermo.com
  • 22. If we were to represent the traditional layered architecture concentrically…Image:http://jeffreypalermo.com
  • 23. A Metaphor Domain-Driven Design (DDD) – The Domain is central to the system – Domain Model Inversion of Control or Separated Interface - Loose coupling based on interfaces at design time, concretes only at runtime Dependency Injection Service Locator Mocking – Application core can be compiled, run, and tested with no infrastructure
  • 24. What else is DDD about? Establishing a Ubiquitous Language between developers and the business Context Primitives of: Entity Value Object Aggregate Root Service Repository Factory Again, good Object Oriented Design
  • 25. Onion ArchitectureS#arp Implementing the Onion Architecture with S#arp
  • 26. S#arp: NOT the Korean Pop Band
  • 27. S#arp History Open source project New BSD license Billy McCafferty has been the primary contributor Hosting CodePlex Google Code github Current stable release: 1.9.6 Latest release: 2.0
  • 28. Components/Dependencies of S#arp 1.9.6 NHibernate 3.0 Fluent NHibernate 1.2 Castle Windsor 2.5.1 Microsoft Practices Service Locator 1.0 ASP.NET MVC 3
  • 29. S#arp 2.0 NHibernate 3.2 Fluent NHibernate 1.3 Castle Core/Windsor 2.5.2/2.5.3 *.Web.Controllers will not be a separate project ApplicationServices project renamed Tasks
  • 30. So, what does S#arp give me? “…this is a solid architectural foundation for rapidly building maintainable web applications leveraging the ASP.NET MVC framework with NHibernate.” Pre-configuration leveraging convention-over- configuration and Fluent NHibernate Auto Persistence Model Extensible via Fluent NHibernate Convention objects
  • 31. So, what does S#arp give me? Tokenized T4 templates for scaffolding CRUD forms-over-data applications Additional layering goodness with the CrudScaffoldingForEnterpriseApp templates Controllers use Application Services/Tasks layer which wraps Repositories, as opposed to dropping Repositories directly into Controllers Uses NHibernate Named Queries for additional control and improved performance Object validation framework
  • 32. So, what does S#arp give me? The Anti-LightSwitch for simple CRUD forms- over-data applications – think: What if VS LightSwitch didn’t suck?? What if it actually used best practices?? What if it really was as extensible as they claim??
  • 33. Caveats and Compromises DDD No-Nos: Domain classes should inherit from SharpArch.Core.DomainModel’s Entity (sets up an integer key) or EntityWithTypedId<T> Deep inheritance chain – Entity : EntityWithTypedId<T> : ValidatableObject : BaseObject – not very hip  NHibernate.Validator reference in Core (Domain) project by default Domain classes have all virtual properties because of NHibernate
  • 34. Caveats and Compromises Typical Open-source caveats Some pieces are buggy Luckily, primarily around the generated pieces – not the framework itself Some pieces are clunky Code generation pieces have manual setup, clunky to change Database tables require manual setup – not a big deal, but an obvious exclusion from all the automatic built-in stuff Documentation is relatively poor – especially because of all the hosting transitions Not an incredibly active project
  • 35. S#arp Architecture Contrib Project Additional support for common scenarios Easy logging of any and all methods – via Assembly Attribute Transactions and Units of Work – via Method Attributes Extends S#arp to work well outside the ASP.NET environment Uses AOP to do much of its work, via PostSharp and Castle Interceptors Current release: 0.2.0 Very inactive project – last check-ins in February 2011
  • 36. S#arp Architecture Contrib ProjectPlanned features: Support and Guidance for Windows GUI and Windows Service Applications Logging Controlled by an Attribute NHibernate Transaction and Session Management Attributes for Windows Applications and Services Transactions Optionally Participate in System.Transaction Transactions (TransactionScope) Support and Guidance for Using Rhino Security (not available in first beta)
  • 37. Onion Architecture S#arpImplementing the Onion Architecture with S#arp
  • 38. Your First S#arp Solution Install MVC 3 - http://www.asp.net/mvc/mvc3 Install Templify - https://github.com/endjin/Templify/downloads Download and install Templify template for S#arp 1.9.6 Rt. Click a folder in Windows Explorer and “Templify Here” – choose the S#arp 1.9.6 template and a project name Choose the project name carefully as this is reflected in directories, namespaces, project names, etc.
  • 39. Your First S#arp Solution Open the solution, and under the CrudScaffolding or CrudScaffoldingForEnterpriseApp project open the ScaffoldingGeneratorCommand T4 Setup the object name and properties for the Domain object you want to create Set the ScaffoldingGenerator path to reflect the root of your solution Uncomment the generator.Run() statement, save the T4, and recomment the generator.Run()
  • 40. Your First S#arp Solution Modify the DB connection string in the $SolutionName$.Web project, NHibernate.config file Create the corresponding table in the app DB for the object you created earlier, adding an int Id column Create a DB table called hibernate_unique_key with a single bigint column named next_hi – insert one row with a starting value of 1 – this is the seed used for int Id columns
  • 41. Bugs Modify this line in $SolutionName$.WebCastleWindsorCompone ntRegistrar.cs: container.Register(Component.For(typeof( IValidator)) .ImplementedBy(typeof(Validator)) .Named("validator")); To read: container.Register(Component.For(typeof(SharpArch. Core.CommonValidator.IValidator)) .ImplementedBy(typeof(Validator)) .Named("validator"));
  • 42. Bugs Comment out this line in Application_Start of Global.asax.cs: ModelValidatorProviders.Providers.Add(new NHibernateValidatorProvider());
  • 43. Demo
  • 44. Let’s Do This Ourselves Well, with help from Tony Sneed http://blog.tonysneed.co m/2011/10/08/peeling- back-the-onion- architecture/
  • 45. Resources Jeffery Palermo’s Blog http://jeffreypalermo.com/ http://jeffreypalermo.com/blog/the-onion-architecture-part-1/ S#arp Architecture Framework http://www.sharparchitecture.net/ https://github.com/sharparchitecture/sharp-architecture/ Domain-Driven Design http://domaindrivendesign.org/ http://www.infoq.com/minibooks/domain-driven-design-quickly Other www.Centare.com blog.GaryPedretti.com – my blog
  • 46. Thank You!! Gary.Pedretti@Centare.com