Ehsan Ghanbari

Experience, DotNet, Solutions

Simple command handler in .net

 

I want to introduce a simple command handler pattern in order to separate commands and queries of your applications if it’s needed. Sometimes especially in large-scale applications, you need to have two layers for reading and write separated and assign two teams to work on them.

You can use the pattern in this post based on the complexity and needs of your application. I recommend that don’t call this CQRS pattern as it’s something completely different and more complex.

 

Get started and Create an interface with no any member:

public interface ICommand

    {

    }

You will see later in this blog post that ICommand is just a flag to determine the commands for the handler. Every command which is trying to make a change in application’s state should return a result. so create another interface named ICommandResult

public interface ICommandResult

    {

        string Message { get; }

        bool Success { get; }

    }

implement the above interface as CommandResult and derive the FailureResult and SuccessResult classes from:

internal abstract class CommandResult : ICommandResult

    {

        public string Message { get; protected set; }

        public bool Success { get; protected set; }

    }



internal class FailureResult : CommandResult

    {

        public FailureResult(string message)

        {

            Success = false;

            Message = message;

        }

    }



    internal class SuccessResult : CommandResult

    {

        public SuccessResult(string message)

        {

            Success = true;

            Message = message;

        }

    }

Now create an interface for handling the validations in CommandBus class:

internal interface IValidationHandler<in TCommand> where TCommand : ICommand

    {

        IEnumerable<ValidationResult> Validate(TCommand command);

    }

 And create a class for validations:

public class ValidationResult

    {

        /// <summary>

        /// Initializes a new instance of the <see cref="ValidationResult"/> class.

        /// </summary>

        public ValidationResult()

        {

        }



        /// <summary>

        /// Initializes a new instance of the <see cref="ValidationResult"/> class.

        /// </summary>

        /// <param name="memeberName">Name of the memeber.</param>

        /// <param name="message">The message.</param>

        public ValidationResult(string memeberName, string message)

        {

            MemberName = memeberName;

            Message = message;

        }



        /// <summary>

        /// Initializes a new instance of the <see cref="ValidationResult"/> class.

        /// </summary>

        /// <param name="message">The message.</param>

        public ValidationResult(string message)

        {

            Message = message;

        }



        /// <summary>

        /// Gets or sets the name of the member.

        /// </summary>

        /// <value>

        /// The name of the member.  May be null for general validation issues.

        /// </value>

        public string MemberName { get; set; }



        /// <summary>

        /// Gets or sets the message.

        /// </summary>

        /// <value>

        /// The message.

        /// </value>

        public string Message { get; set; }

    }

And now create the most used interface in this pattern. ICommandBus will be called as bus handler in every command:

public interface ICommandBus

    {

        ICommandResult Send<TCommand>(TCommand command) where TCommand : ICommand;

        IEnumerable<ValidationResult> Validate<TCommand>(TCommand command) where TCommand : ICommand;

    }

To implementing this interface, create a class again with the following definition:

  internal class CommandBus : ICommandBus

    {

        public ICommandResult Send<TCommand>(TCommand command) where TCommand : ICommand

        {

            var handler = DependencyResolver.Current.GetService<ICommandHandler<TCommand>>();



            if (!((handler != null) && handler != null))

            {

                throw new CommandHandlerNotFoundException(typeof(TCommand));

            }

            return handler.Execute(command);

        }



        public IEnumerable<ValidationResult> Validate<TCommand>(TCommand command) where TCommand : ICommand

        {

            var handler = DependencyResolver.Current.GetService<IValidationHandler<TCommand>>();

         

            if (!((handler != null) && handler != null))

            {

                throw new ValidationHandlerNotFoundException(typeof(TCommand));

            }

            return handler.Validate(command);

        }

    }

The above class will handle every command received from the bus. And now for executing the handler or so-called for implementing the business, you need an interface:

internal interface ICommandHandler<in TCommand> where TCommand : ICommand

    {

        ICommandResult Execute(TCommand command);

    }

And finally as I’m personally interested in to have my own exception handler, so I create a customized handler:

public class CommandHandlerNotFoundException : Exception

    {

        public CommandHandlerNotFoundException(Type type)

            : base(string.Format("Command handler not found for command type: {0}", type))

        {

        }

    }



    internal class ValidationHandlerNotFoundException : Exception

    {

        public ValidationHandlerNotFoundException(Type type)

            : base(string.Format("Validation handler not found for command type: {0}", type))

        {

        }

    }

Finished! Now let’s use the above codes in a real work application. We are going to handle the products of an e-commerce application as its business is easier to comprehend for everybody:

    public interface IProductCommand : ICommand

    {

        string Name { get; set; }



        string OriginalName { get; set; }



        string Description { get; set; }



        decimal Price { get; set; }

     

    }

  

    public class ProductCommand : IProductCommand

    {

        public string Name { get; set; }



        public string OriginalName { get; set; }



        public string Description { get; set; }



        public decimal Price { get; set; }     

    }



    public class CreateProductCommand : ProductCommand

    {

    }



    public class EditProductCommand : ProductCommand

    {

        public Guid ProductId { get; set; }



        public DateTime CreationDate { get; set; }



        public DateTime LastUpdateDate { get; set; }

    }



public class DeleteProductCommand : ICommand

    {

        public Guid[] ProductIds { get; set; }

    }

You can see that I created an interface derived from ICommand named IProductCommand and finally created the target classes. And at the end we should create the Product handler class:

internal partial class ProductCommandHandler :

        ICommandHandler<CreateProductCommand>,

        ICommandHandler<EditProductCommand>,   

        ICommandHandler<DeleteProductCommand>       

    {

        private readonly IProductRepository _productRepository;

        private readonly IMembershipRepository _membershipRepository;     

        private readonly IUnitOfWork _unitOfWork;

        private readonly ICacheManager _cacheManager;

        private readonly ILogger _logger;



        public ProductCommandHandler(

            IProductRepository productRepository,        

            IUnitOfWork unitOfWork,

            ILogger logger,

            ICacheManager cacheManager)

        {

            _productRepository = productRepository;          

            _unitOfWork = unitOfWork;

            _logger = logger;

            _cacheManager = cacheManager;        

        }

       

        public ICommandResult Execute(CreateProductCommand command)

        {

            try

            {

                if (command == null)

                {

                    throw new ArgumentNullException();

                }



                var product = new Product();

                AddProductAppurtenance(command, product);

                _productRepository.Add(product);

                _unitOfWork.Commit();

                return new SuccessResult(ProductCommandMessage.ProductCreatedSuccessfully);

            }

            catch (Exception exception)

            {

                _logger.Error(exception.Message);

                return new FailureResult(ProductCommandMessage.ProductCreationFailed);

            }

        }



        public ICommandResult Execute(EditProductCommand command)

        {

            try

            {

                if (command == null)

                {

                    throw new ArgumentNullException();

                }



                var product = _productRepository.GetProductDetailById(command.ProductId);

                ClearProductAppurtenance(product);

                AddProductAppurtenance(command, product);

                _productRepository.Edit(product);

                _unitOfWork.Commit();



                return new SuccessResult(ProductCommandMessage.ProductEditedSuccessfully);

            }

            catch (Exception exception)

            {

                _logger.Error(exception.Message);

                return new FailureResult(ProductCommandMessage.ProductEditionFailed);

            }

        }



        public ICommandResult Execute(DeleteProductCommand command)

        {

            if (command.ProductIds == null)

            {

                throw new ArgumentNullException();

            }



            var exceptions = new List<Exception>();

            foreach (var productId in command.ProductIds)

            {

                try

                {

                    var product = DeleteProduct(productId);

                    _productRepository.Edit(product);

                }

                catch (Exception exception)

                {

                    exceptions.Add(exception);

                    return new FailureResult(ProductCommandMessage.ProductDeletionFailed);

                }

            }



            if (exceptions.Any())

            {

                throw new AggregateException(exceptions);

            }



            _unitOfWork.Commit();

            return new SuccessResult(ProductCommandMessage.ProductsDeletedSuccessufully);

        }  

 

We used all of the classes introduced in infrastructure.

Note 1: so you need to have an IOC container tool, to the best of my Knowledge, AsClosedTypesOf in Autofac resolves the ICommandHandler. This a piece of code I wrote for IOC handler:

  public class CommandModule : Module

    {

        protected override void Load(ContainerBuilder builder)

        {

            builder.RegisterModule<RepositoryModule>();

            builder.RegisterType<CommandBus>().As<ICommandBus>().InstancePerRequest();

            builder.RegisterAssemblyTypes(ThisAssembly).AsClosedTypesOf(typeof(ICommandHandler<>)).InstancePerRequest();

        }

    }

Note 2: a penny for your thoughts! how to use ICommandBus!? See the below piece of code as an example:

[HttpPost]

        public JsonResult DeleteProduct(DeleteProductCommand command)

        {

            var result = _commandBus.Send(command);

            return JsonMessage(result);

        }

have fun.



Difference between layer super type and template method patterns

About two days ago I asked a question about the differences of these two patterns. after reading about the template method patterns in detail I found that although there are lots of similarities between them but layer super type is not the same as method template and vice versa. I've blogged about Layer Super type before in here, now I want to talk about method template pattern. Basically template method is to run common functionality of a base class from the child class and use the objects of the child type in the common method functionality of the base type. It means that the best way of implementing the pattern is to create a base abstract class with abstract methods to implement the implementer of the base abstract class members.  Take a look this sample in C#:

  1.  public abstract class Order
  2.     {
  3.         protected abstract bool CheckAccountAmount();
  4.         protected abstract bool CheckProductAvailibility();
  5.  
  6.         public bool MakeOrder()
  7.         {
  8.             if (CheckAccountAmount())
  9.             {
  10.                 if (CheckProductAvailibility())
  11.                 {
  12.                     //Do Order process
  13.                 }
  14.                 else
  15.                 {
  16.                     return false;
  17.                 }
  18.                 return false;
  19.             }
  20.             return false;
  21.         }
  22.     }
  23.  
  24.  
  25.     public class Customer : Order
  26.     {
  27.         protected override bool CheckAccountAmount()
  28.         {
  29.             // recieve the information from credit card servers
  30.             return true;
  31.         }
  32.  
  33.         protected override bool CheckProductAvailibility()
  34.         {
  35.             // go to the database to see if the product is available
  36.             return true;
  37.         }
  38.     }
  39.  
  40.  
  41.     public class Member : Order
  42.     {
  43.         protected override bool CheckAccountAmount()
  44.         {
  45.             // go to the database to check if the members has enough account in his/her account
  46.             return true;
  47.         }
  48.  
  49.         protected override bool CheckProductAvailibility()
  50.         {
  51.             //  // go to the database to see if the product is available
  52.             return true;
  53.         }
  54.     }
  55.  
  56.  
  57.     public class Presentation
  58.     {
  59.         public void Operatio()
  60.         {
  61.             //call customer methods for order
  62.             Order customer = new Customer();
  63.             customer.MakeOrder();
  64.  
  65.             //call member methods for order
  66.             Order member = new Member();
  67.             member.MakeOrder();
  68.         }
  69.     }
  70.  

 

As you can see, there are some common operation in both Member and Customer, I've created the MakeOrder method in base class to be available for member and Customer. Making Order is a common task for Member and Customer on creating order and each of them can use it for its own order process. Making order is just for making order and works only for it! I mean that It's a common task for making order in the system but what do you think about creating basket for customers and members? Can you use the same method (MakeOrder)? you should create another base class for it yeah?

the main goal of this blog post is to define the differences of template method pattern and layer super type. If you have a look on my post about the layer super type you can see that there are more similarities between them. Both of them reduce the duplication and reimplementation of code. I'm agree with Adriano comment on my question, it's better to talk about the similarities than differences of these patterns. But I think that template method patterns works on the same implementation of subtypes and redefine certain steps of an algorithm without changing the Algorithm's Structure. And it's mostly about sequential and common processes but layer super type works on similarities of some operation on types and it's A type that acts as the supertype for all types in its layer.



Implementing thread safe Singleton pattern in C#

A singleton is a class which allows one instance of itself to be created and allow you to easy access to that instance. A singleton just gives you a single instance of a class. When you need a class that has only one instance. Singleton ensures you that a class has only one instance and also you have a global point to access that instance. This a simple example of singleton pattern.

 

  1.     public class ThreadSafeSingleton
  2.     {
  3.         private static volatile ThreadSafeSingleton _instance;
  4.         private static readonly object Sync= new Object();
  5.  
  6.         private ThreadSafeSingleton()
  7.         {
  8.         }
  9.  
  10.         public static ThreadSafeSingleton Instance
  11.         {
  12.             get
  13.             {
  14.                 if (_instance == null)
  15.                 {
  16.                     lock (Sync)
  17.                     {
  18.                         if (_instance == null)
  19.                         {
  20.                             _instance = new ThreadSafeSingleton();
  21.                         }
  22.                     }
  23.                 }
  24.  
  25.                 return _instance;
  26.             }
  27.         }
  28.     }

 

The benefit of implementing Singleton:

  1. Ensuring that all objects access the single instance.
  2. The class has the flexibility to change the instantiation process.
  3. By changing in one instance you can change all instances of a class.

 

 

Read these articles for complete information

  1. http://www.yoda.arachsys.com/csharp/singleton.html
  2. http://csharpindepth.com/articles/general/singleton.aspx



When to use dependency injection?

In enterprise applications, when it comes to a large amount of data and different components and you are aiming for code reuse; there is a pattern named Dependency Injection to avoid tight coupling of object implementations and make the objects loosely coupled. It can be applied in any situation across the layers, but it doesn't mean that you should apply for DI everywhere!

 

If you don't need different implementation and different configuration Do not use Dependency injection. Although there are some related and of course older replacement patterns for DI such as abstract factory or container patterns, nut dependency injection makes the code testable as well, and it is one the biggest advantage of DI in compare to other similar patterns.

 



Dependency Inversion of SOLID principle

As you know, Dependency Inversion Principle is the last principle of SOLID. I talked about SOLID principle and fundamental in my previous post that was about SRP. Now I'm gonna to consider the dependency inversion of SOLID. Based on definition "High level modules should not depend upon low level module, both should be depend upon abstraction". Or in other definition "abstraction should not depend upon details, details should depend upon abstraction". When you have relationship between you classes in OPP, that relationship should be stated on terms of abstraction rather than concrete implementation. "The benefits of using loose coupling aren’t always instantly evident, but they become visible over time, as the complexity of a code grows." in concrete implementaion changes to one class will break the other class.

Take a look at this implementation:

  1.    public class OrderRepository
  2.     {
  3.         public void Add()
  4.         {
  5.             //Add Order
  6.         }
  7.      }
  8.  
  9.     public class OrderService
  10.     {
  11.         private readonly  OrderRepository _orderRepository;
  12.     
  13.         public OrderService()
  14.         {
  15.             _orderRepository = new OrderRepository();
  16.         }
  17.  
  18.         public void CreateOrder()
  19.         {
  20.             _orderRepository.Add();
  21.         }
  22.      }

 

I just create an instance of the OrderRepository inside the OrderService to use the add method. As you know every changes in OrderRepository will destroy the OrderService class and we should modify the OrderService class every times. Now notice about this implementation:

 

  1.     public interface  IOrderRepository
  2.     {
  3.         void Add();
  4.     }
  5.  
  6.     public class OrderRepository :IOrderRepository
  7.     {
  8.         public void Add()
  9.         {
  10.             throw new NotImplementedException();
  11.         }
  12.     }
  13.  
  14.    public class OrderService
  15.     {
  16.         private readonly IOrderRepository _orderRepository;
  17.  
  18.         public OrderService(IOrderRepository orderRepository)
  19.         {
  20.             _orderRepository = orderRepository;
  21.         }
  22.     
  23.         public void CreateOrder()
  24.         {
  25.             _orderRepository.Add();
  26.         }
  27.     }

 

I just added an interface, but if you take a deeper look at OrderService,it doesn't have any concrete instantiating of OrderRepository and every change in IOrderRepository should be implemented in OrderRepository and OrderService just talks to IOrderService. (Don't call use we'll call you!). I also used constructor injection that you can read more about that here.

 

You can read more about DIP

  1. http://www.codeproject.com/Articles/495019/Dependency-Inversion-Principle-and-the-Dependency
  2. http://lostechies.com/derickbailey/2011/09/22/dependency-injection-is-not-the-same-as-the-dependency-inversion-principle/



About Me

Ehsan Ghanbari

Hi! my name is Ehsan. I'm a developer, passionate technologist, and fan of clean code. I'm interested in enterprise and large-scale applications architecture and design patterns. I spend a lot of time on software architecture. Since 2008, I've been as a developer for different companies and organizations and I've been focusing on Microsoft ecosystem all the time. During the past years, Read More

Post Tags
Pending Blog Posts
using Elmah in asp.net MVC4
Using FluentSecurity in MVC
Strategic design
Factory Pattern
time out pattern in ajax
Redis as a cache server
How to use PagedList In asp.net MVC
Multiple submit buttons in asp.net MVC
Domain driven design VS model driven architecture
What's the DDD-lite?