APPLIED PATTERNS
The current project implementation
TOPICS
 SOLID
 Repository pattern
 Unit of Work pattern
 Decorator pattern
SOLID
 Single Responsibility Principle
 “a class should have only a single responsibility”
 Open/closed Principle
 “software entities … should be open for extension, but closed
for modification.”
 Liskov substitution principle
 “objects in a program should be replaceable with instances of
their subtypes without altering the correctness of that
program.”
 Interface segregation principle
 ““many client-specific interfaces are better than one general-
purpose interface.”
 Dependency inversion principle
 one should “Depend upon Abstractions. Do not depend upon
concretions.”
REPOSITORY PATTERN
 Abstraction data access
 Database
 Services
 Files
 Etc.
 Hide implementation details
SEPERATION
 Repository.Database
 Database context
 Initializers
 Migrations
 Scripts
 Repository.Entities
 Entity objects (POCO)
 Repository.DataAccess
 Repository abstraction layer
REPOSITORY INTERFACE
public interface IRepository<TEntity>
where TEntity : class
{
IEnumerable<TEntity> Get(
Expression<Func<TEntity, bool>> filter = null,
Func<IQueryable<TEntity>,
IOrderedQueryable<TEntity>> orderBy = null,
string includeProperties = "");
TEntity GetById(object id);
TEntity Insert(TEntity entity);
TEntity Delete(object id);
TEntity Delete(TEntity entityToDelete);
void Update(TEntity entityToUpdate);
}
REPOSITORY IMPLEMENTATION
public Repository(DatabaseContext context)
{
this.context = context;
this.dbSet = context.Set<TEntity>();
}
DI REGISTRATION
builder.RegisterGeneric(typeof(Repository<>))
.As(typeof(IRepository<>));
builder.RegisterType<DatabaseContext>()
.AsSelf()
.InstancePerLifetimeScope();
USAGE
protected StoreNewQueueItem(
IRepository<ProcessQueue> processQueueRepository,
...)
{
this.processQueueRepository = processQueueRepository;
...
}
...
var insertedItem = processQueueRepository
.Insert(queueItem);
...
UNIT OF WORK PATTERN
 “A Unit of Work keeps track of everything you do
during a business transaction that can affect the
database. When you're done, it figures out
everything that needs to be done to alter the
database as a result of your work.”
SOURCE: http://www.martinfowler.com/eaaCatalog/unitOfWork.html
 Committing changes
 Handling of transaction
COMMON REPOSITORY USAGE
var insertedItem = processQueueRepository
.Insert(queueItem);
processQueueRepository.Save();
OR
public virtual TEntity Insert(
TEntity entity)
{
var insertedItem = dbSet.Add(entity);
context.SaveChanges();
return insertedItem;
}
UNIT OF WORK + REPOSITORY
public class MyCommand
{
private readonly IUnitOfWorkFactory factory;
public MyCommand(IUnitOfWorkFactory factory)
{
this.factory = factory;
}
public void Execute()
{
using (var context = this.factory.CreateNew())
{
this.DoSomeNiceThings(context);
context.Commit();
}
}
}
SOURCE: http://stackoverflow.com/a/4944201/352640
NOT A GOOD IMPLEMENTATION
 UoW + Repository, great idea
 Some of the greater developer minds are
opponents
 Violates some principles
 Opaque dependencies
 Open/closed principle
 Single Responsibility Principle
 Nominal abstraction
BETTER IMPLEMENTATION?
 List of example implementations:
SOURCE: https://lostechies.com/derekgreer/2015/11/01/survey-of-entity-framework-unit-of-work-
patterns/
 Unit of Work Decorator
 Works everywhere
 Close to point of need
 More control
 Setup is hard!
DECORATOR PATTERN
 “…the decorator pattern … allows behavior to be
added to an individual object … without
affecting the behavior of other objects from the
same class.
The decorator pattern is often useful for adhering to
the Single Responsibility Principle, as it allows
functionality to be divided between classes with
unique areas of concern.”
SOURCE: https://en.wikipedia.org/wiki/Decorator_pattern
 Extending functionality
 Adhering SRP
DECORATOR PATTERN CLASS DIAGRAM
 Decorator implements same interface
DECORATOR PATTERN EXAMPLE
/// <summary>
/// The 'Component' abstract class
/// </summary>
abstract class Component
{
public abstract void Operation();
}
/// <summary>
/// The 'Decorator' abstract class
/// </summary>
abstract class Decorator : Component
{
protected Component component;
public void SetComponent(Component component)
{
this.component = component;
}
public override void Operation()
{
if (component != null)
{
component.Operation();
}
}
}
static void Main()
{
// Create ConcreteComponent and two Decorators
ConcreteComponent c = new ConcreteComponent();
ConcreteDecoratorA d1 = new ConcreteDecoratorA();
ConcreteDecoratorB d2 = new ConcreteDecoratorB();
// Link decorators
d1.SetComponent(c);
d2.SetComponent(d1);
d2.Operation();
}
/// <summary>
/// The 'ConcreteComponent' class
/// </summary>
class ConcreteComponent : Component
{
public override void Operation()
{
Console.WriteLine("ConcreteComponent.Operation()");
}
}
/// <summary>
/// The 'ConcreteDecoratorA' class
/// </summary>
class ConcreteDecoratorA : Decorator
{
public override void Operation()
{
base.Operation();
Console.WriteLine("ConcreteDecoratorA.Operation()");
}
}
/// <summary>
/// The 'ConcreteDecoratorB' class
/// </summary>
class ConcreteDecoratorB : Decorator
{
public override void Operation()
{
base.Operation();
AddedBehavior();
Console.WriteLine("ConcreteDecoratorB.Operation()");
}
void AddedBehavior()
{
}
}
PUTTING IT ALL TOGETHER
 Create handler
 Query
 Command
 Repository
 Repository actions
 Create decorator
 Committing changes
USAGE THE TRANSACTION DECORATOR
public class TransactionRequestHandlerDecorator<...> :
IConvertorCommandHandler<...>
{
private readonly IConvertorCommandHandler<...> decorated;
private readonly MyDatabaseContext context;
public TransactionRequestHandlerDecorator(
IConvertorCommandHandler<...> decorated,
MyDatabaseContext context)
{
this.decorated = decorated;
this.context = context;
}
public void Handle(TCommand command)
{
Log.Debug("Starting new transaction.");
using (var transaction = context.Database.BeginTransaction())
{
try
{
decorated.Handle(command);
context.SaveChanges();
Log.Debug("Saving changes.");
transaction.Commit();
Log.Debug("Comitting the transaction.");
}
...
DECORATOR REGISTRATION
foreach (var commandHandler in commandHandlers)
{
builder.RegisterGeneric(commandHandler)
.Named("commandHandler",
typeof(IConvertorCommandHandler<,,>));
}
builder.RegisterGenericDecorator(
typeof(TransactionRequestHandlerDecorator<,,>),
typeof(IConvertorCommandHandler<,,>),
fromKey: "commandHandler")
.Named("decorated",
typeof(IConvertorCommandHandler<,,>));
QUESTIONS?

Applied patterns in the project

  • 1.
    APPLIED PATTERNS The currentproject implementation
  • 2.
    TOPICS  SOLID  Repositorypattern  Unit of Work pattern  Decorator pattern
  • 3.
    SOLID  Single ResponsibilityPrinciple  “a class should have only a single responsibility”  Open/closed Principle  “software entities … should be open for extension, but closed for modification.”  Liskov substitution principle  “objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program.”  Interface segregation principle  ““many client-specific interfaces are better than one general- purpose interface.”  Dependency inversion principle  one should “Depend upon Abstractions. Do not depend upon concretions.”
  • 4.
    REPOSITORY PATTERN  Abstractiondata access  Database  Services  Files  Etc.  Hide implementation details
  • 5.
    SEPERATION  Repository.Database  Databasecontext  Initializers  Migrations  Scripts  Repository.Entities  Entity objects (POCO)  Repository.DataAccess  Repository abstraction layer
  • 6.
    REPOSITORY INTERFACE public interfaceIRepository<TEntity> where TEntity : class { IEnumerable<TEntity> Get( Expression<Func<TEntity, bool>> filter = null, Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null, string includeProperties = ""); TEntity GetById(object id); TEntity Insert(TEntity entity); TEntity Delete(object id); TEntity Delete(TEntity entityToDelete); void Update(TEntity entityToUpdate); }
  • 7.
    REPOSITORY IMPLEMENTATION public Repository(DatabaseContextcontext) { this.context = context; this.dbSet = context.Set<TEntity>(); }
  • 8.
  • 9.
    USAGE protected StoreNewQueueItem( IRepository<ProcessQueue> processQueueRepository, ...) { this.processQueueRepository= processQueueRepository; ... } ... var insertedItem = processQueueRepository .Insert(queueItem); ...
  • 10.
    UNIT OF WORKPATTERN  “A Unit of Work keeps track of everything you do during a business transaction that can affect the database. When you're done, it figures out everything that needs to be done to alter the database as a result of your work.” SOURCE: http://www.martinfowler.com/eaaCatalog/unitOfWork.html  Committing changes  Handling of transaction
  • 11.
    COMMON REPOSITORY USAGE varinsertedItem = processQueueRepository .Insert(queueItem); processQueueRepository.Save(); OR public virtual TEntity Insert( TEntity entity) { var insertedItem = dbSet.Add(entity); context.SaveChanges(); return insertedItem; }
  • 12.
    UNIT OF WORK+ REPOSITORY public class MyCommand { private readonly IUnitOfWorkFactory factory; public MyCommand(IUnitOfWorkFactory factory) { this.factory = factory; } public void Execute() { using (var context = this.factory.CreateNew()) { this.DoSomeNiceThings(context); context.Commit(); } } } SOURCE: http://stackoverflow.com/a/4944201/352640
  • 13.
    NOT A GOODIMPLEMENTATION  UoW + Repository, great idea  Some of the greater developer minds are opponents  Violates some principles  Opaque dependencies  Open/closed principle  Single Responsibility Principle  Nominal abstraction
  • 14.
    BETTER IMPLEMENTATION?  Listof example implementations: SOURCE: https://lostechies.com/derekgreer/2015/11/01/survey-of-entity-framework-unit-of-work- patterns/  Unit of Work Decorator  Works everywhere  Close to point of need  More control  Setup is hard!
  • 15.
    DECORATOR PATTERN  “…thedecorator pattern … allows behavior to be added to an individual object … without affecting the behavior of other objects from the same class. The decorator pattern is often useful for adhering to the Single Responsibility Principle, as it allows functionality to be divided between classes with unique areas of concern.” SOURCE: https://en.wikipedia.org/wiki/Decorator_pattern  Extending functionality  Adhering SRP
  • 16.
    DECORATOR PATTERN CLASSDIAGRAM  Decorator implements same interface
  • 17.
    DECORATOR PATTERN EXAMPLE ///<summary> /// The 'Component' abstract class /// </summary> abstract class Component { public abstract void Operation(); } /// <summary> /// The 'Decorator' abstract class /// </summary> abstract class Decorator : Component { protected Component component; public void SetComponent(Component component) { this.component = component; } public override void Operation() { if (component != null) { component.Operation(); } } } static void Main() { // Create ConcreteComponent and two Decorators ConcreteComponent c = new ConcreteComponent(); ConcreteDecoratorA d1 = new ConcreteDecoratorA(); ConcreteDecoratorB d2 = new ConcreteDecoratorB(); // Link decorators d1.SetComponent(c); d2.SetComponent(d1); d2.Operation(); } /// <summary> /// The 'ConcreteComponent' class /// </summary> class ConcreteComponent : Component { public override void Operation() { Console.WriteLine("ConcreteComponent.Operation()"); } } /// <summary> /// The 'ConcreteDecoratorA' class /// </summary> class ConcreteDecoratorA : Decorator { public override void Operation() { base.Operation(); Console.WriteLine("ConcreteDecoratorA.Operation()"); } } /// <summary> /// The 'ConcreteDecoratorB' class /// </summary> class ConcreteDecoratorB : Decorator { public override void Operation() { base.Operation(); AddedBehavior(); Console.WriteLine("ConcreteDecoratorB.Operation()"); } void AddedBehavior() { } }
  • 18.
    PUTTING IT ALLTOGETHER  Create handler  Query  Command  Repository  Repository actions  Create decorator  Committing changes
  • 19.
    USAGE THE TRANSACTIONDECORATOR public class TransactionRequestHandlerDecorator<...> : IConvertorCommandHandler<...> { private readonly IConvertorCommandHandler<...> decorated; private readonly MyDatabaseContext context; public TransactionRequestHandlerDecorator( IConvertorCommandHandler<...> decorated, MyDatabaseContext context) { this.decorated = decorated; this.context = context; } public void Handle(TCommand command) { Log.Debug("Starting new transaction."); using (var transaction = context.Database.BeginTransaction()) { try { decorated.Handle(command); context.SaveChanges(); Log.Debug("Saving changes."); transaction.Commit(); Log.Debug("Comitting the transaction."); } ...
  • 20.
    DECORATOR REGISTRATION foreach (varcommandHandler in commandHandlers) { builder.RegisterGeneric(commandHandler) .Named("commandHandler", typeof(IConvertorCommandHandler<,,>)); } builder.RegisterGenericDecorator( typeof(TransactionRequestHandlerDecorator<,,>), typeof(IConvertorCommandHandler<,,>), fromKey: "commandHandler") .Named("decorated", typeof(IConvertorCommandHandler<,,>));
  • 21.

Editor's Notes

  • #4 SOLID principles are basis for good, maintainable software SRP = Class & method should only do 1 thing Open/Closed = “Open for extension, closed for modification”, overerving en polymorfisme, interfaces, abstracte klassen Liskov = S is subtype of T, then T should be able to be replaced by S. Works with contravariance & covariance Interface segregation principle = Generating specific interfaces, not too generic with unused methods for some implementations. DI = Decoupling of modules
  • #6 Plain old CLR Object
  • #7 Inspiration by https://www.asp.net/mvc/overview/older-versions/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application All CRUD actions are defined
  • #8 Generic repository layer You can imagine how the different CRUD actions are implemented The basis is defined over here: https://www.asp.net/mvc/overview/older-versions/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application
  • #9 Create a single context per lifetime. Lifetimes shall be created per action. In web applications this can be created per request
  • #10 Constructor injection of respository Using to insert an item to the database
  • #11 Doing a ‘unit of work’. Business logic, common in DDD scenarios
  • #12 Repository is responsible for making transactions or committing them. What if transaction should be on multiple repository impelementations or more control over making changes/transactions. Unit of Work to the rescue
  • #13 Creating a unit of work scope Do your work inside this scope, like adding, deleting, querying, updating Commit your changes in the end
  • #14 First, this approach leads to opaque dependencies. Due to the fact that classes interact with repositories through the UnitOfWork instance, the client interface doesn’t clearly express the inherent business-level collaborators it depends upon (i.e. any aggregate root collections). Second, this violates the Open/Closed Principle. To add new aggregate roots to the system requires modifying the UnitOfWork each time. Third, this violates the Single Responsibility Principle. The single responsibility of a Unit of Work implementation should be to encapsulate the behavior necessary to commit or rollback an set of operations atomically. The instantiation and management of repositories or any other component which may wish to enlist in a unit of work is a separate concern. Lastly, this results in a nominal abstraction which is semantically coupled with Entity Framework. The example code for this approach sets forth an interface to the UnitOfWork implementation which isn’t the approach used in the aforementioned Microsoft article. Whether you take a dependency upon the interface or the implementation directly, however, the presumption of such an abstraction is to decouple the application from using Entity Framework directly. While such an abstraction might provide some benefits, it reflects Entity Framework usage semantics and as such doesn’t really decouple you from the particular persistence technology you’re using. While you could use this approach with another ORM (e.g. NHibernate), this approach is more of a reflection of Entity Framework operations (e.g. it’s flushing model) and usage patterns. As such, you probably wouldn’t arrive at this same abstraction were you to have started by defining the abstraction in terms of the behavior required by your application prior to choosing a specific ORM (i.e. following The Dependency Inversion Principle). You might even find yourself violating the Liskof Substitution Principle if you actually attempted to provide an alternate ORM implementation. Given these issues, I would advise people to avoid this approach. https://lostechies.com/derekgreer/2015/11/01/survey-of-entity-framework-unit-of-work-patterns/ https://lostechies.com/jimmybogard/2012/10/08/favor-query-objects-over-repositories/ http://rob.conery.io/2014/03/04/repositories-and-unitofwork-are-not-a-good-idea/
  • #15 Can be used in web applications as well as in console, windows, wpf, etc. Can add functionality based on the command handlers CommandHandlers used, can also use CQRS better
  • #17 UML diagram: http://www.dofactory.com/net/decorator-design-pattern
  • #18 Creating a component and a decorator Adding the decorators to the component Execute the decorator, which in its turn will execute the component
  • #19 The handler will do all the business work/logic we need to do for the specific ‘request’, which also means talking with the Repository abstraction The handler will be decorated with a Transaction decorator, which will commit the changes Other decorators can be added if necessary
  • #21 Using Autofac First register the command handler as a named type Second, register the decorator, using the name in the `fromKey` and also name the decorator itself, so other decorators can hook into this, using this newly created name