Implementing the
Onion 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.
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
Gary Pedretti
Solutions Manager, Agile Practice
Over 12 years in the software industry – DBA, Developer,
BA, Application Architect
Scrum: Team member, Scrum Master, Coach, Certified
Scrum Trainer for Scrum.org
http://blog.GaryPedretti.com/
@GaryPedretti
http://www.linkedin.com/in/garypedretti
MCPD 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
Onion Architecture
 S#arp

 Implementing the Onion Architecture with
 S#arp

 Custom Code
Let’s Talk Business Logic….Domain
Logic…Behavior…
Fowler and “The Bible”




Four Domain Logic
Patterns
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?
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
3. Service Layer
 Defines an application's boundary with a layer of services that
 establishes a set of available operations and coordinates the
 application's response in each operation
 “Service” - arrrrrggggggghhhhhhhhhh
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
Other Patterns
 Where do these fit in?
 Presentation patterns
 Data Source patterns
Model View Controller…or MVx
 Splits user interface interaction into three distinct
 roles.
 Is this presentation only?
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
Let’s Talk Layers…and Tiers
Traditional Layered Architecture




Images:
http://jeffreypalermo.com
Traditional Layered Architecture – Anemic
Domain?
Image: http://jeffreypalermo.com
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 infrastructure


Source: http://jeffreypalermo.com/blog/the-onion-architecture-part-3/
AKA “Ports and Adapters” or “Object
 Structural” or “Hexagonal Architecture”




Image: http://alistair.cockburn.us/Hexagonal+architecture
AKA “Ports and Adapters” or “Object
Structural” 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
If we were to represent the Onion
Architecture flattened…




Image: http://jeffreypalermo.com
If we were to represent the traditional
   layered architecture concentrically…




Image:
http://jeffreypalermo.com
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
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
Onion Architecture


S#arp

 Implementing the Onion Architecture with
 S#arp
S#arp: NOT the Korean Pop Band
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
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
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
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
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
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??
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
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
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
S#arp Architecture Contrib Project
Planned 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)
Onion Architecture

 S#arp


Implementing the Onion Architecture with S#arp
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.
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()
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
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"));
Bugs
 Comment out this line in Application_Start of
 Global.asax.cs:
   ModelValidatorProviders.Providers.Add(new
   NHibernateValidatorProvider());
Demo
Let’s Do This Ourselves
  Well, with help from
  Tony Sneed
  http://blog.tonysneed.co
  m/2011/10/08/peeling-
  back-the-onion-
  architecture/
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
Thank You!!
 Gary.Pedretti@Centare.com

Onion Architecture with S#arp

  • 1.
    Implementing the Onion 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 ConsultingServices 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 Pedretti Solutions Manager,Agile Practice Over 12 years in the software industry – DBA, Developer, BA, Application Architect Scrum: Team member, Scrum Master, Coach, Certified Scrum Trainer for Scrum.org http://blog.GaryPedretti.com/ @GaryPedretti http://www.linkedin.com/in/garypedretti MCPD 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 BusinessLogic….Domain Logic…Behavior…
  • 6.
    Fowler and “TheBible” Four Domain Logic Patterns
  • 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 application's boundary with a layer of services that establishes a set of available operations and coordinates the application's 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 Wheredo these fit in? Presentation patterns Data Source patterns
  • 12.
    Model View Controller…orMVx Splits user interface interaction into three distinct roles. Is this presentation only?
  • 13.
    Active Record Anobject 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.
  • 15.
  • 16.
  • 18.
  • 19.
    Key Tenets ofOnion 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 infrastructure Source: http://jeffreypalermo.com/blog/the-onion-architecture-part-3/
  • 20.
    AKA “Ports andAdapters” or “Object Structural” or “Hexagonal Architecture” Image: http://alistair.cockburn.us/Hexagonal+architecture
  • 21.
    AKA “Ports andAdapters” or “Object Structural” 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
  • 22.
    If we wereto represent the Onion Architecture flattened… Image: http://jeffreypalermo.com
  • 23.
    If we wereto represent the traditional layered architecture concentrically… Image: http://jeffreypalermo.com
  • 25.
    A Metaphor Domain-DrivenDesign (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
  • 26.
    What else isDDD 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
  • 27.
    Onion Architecture S#arp Implementingthe Onion Architecture with S#arp
  • 28.
    S#arp: NOT theKorean Pop Band
  • 30.
    S#arp History Opensource 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
  • 31.
    Components/Dependencies of S#arp1.9.6 NHibernate 3.0 Fluent NHibernate 1.2 Castle Windsor 2.5.1 Microsoft Practices Service Locator 1.0 ASP.NET MVC 3
  • 32.
    S#arp 2.0 NHibernate3.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
  • 33.
    So, what doesS#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
  • 34.
    So, what doesS#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
  • 35.
    So, what doesS#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??
  • 36.
    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
  • 37.
    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
  • 38.
    S#arp Architecture ContribProject 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
  • 39.
    S#arp Architecture ContribProject Planned 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)
  • 40.
    Onion Architecture S#arp Implementingthe Onion Architecture with S#arp
  • 41.
    Your First S#arpSolution 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.
  • 42.
    Your First S#arpSolution 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()
  • 43.
    Your First S#arpSolution 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
  • 44.
    Bugs Modify thisline 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"));
  • 45.
    Bugs Comment outthis line in Application_Start of Global.asax.cs: ModelValidatorProviders.Providers.Add(new NHibernateValidatorProvider());
  • 46.
  • 47.
    Let’s Do ThisOurselves Well, with help from Tony Sneed http://blog.tonysneed.co m/2011/10/08/peeling- back-the-onion- architecture/
  • 48.
    Resources Jeffery Palermo’sBlog 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
  • 49.

Editor's Notes

  • #7 http://www.amazon.com/Patterns-Enterprise-Application-Architecture-Martin/dp/0321127420/ref=sr_1_1?ie=UTF8&amp;qid=1334844499&amp;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
  • #9 Fowler calls Active Record a Data Source Architectural Pattern, not a Domain Logic Pattern
  • #10 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)
  • #13 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
  • #14 Fowler calls this a Data Source Architectural Pattern
  • #20 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
  • #25 Picture: Meet a Meaningless Metaphor, http://wakefelderman.blogspot.com
  • #26 The Onion Architecture is a great metaphor to help us grasp how these concepts work within a real application.