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.



Disadvantages of n-layered architectures

Most of the people use n-layered architectures in their application developement. There are lots of advantage for n-layered architecture but I want to talk about disadvantages. actually it's not a good idea to design a somplex architecture for every problem , you don't need to apply n-layered architecure in every case because it's mostly about making complex things simple whilst a complex architecture can make a system more and more hard to understand rather than making performance problems. Based on this presentation, making software via n-layered application could be cost effective and dangerous for performance. Suppose an architecture like picture below:

n-layered

 

When you make a request from your browser your request goes throw several layers and assemblies to persist your request in data base and then comes back the same way to make a change (you can simply assume the scenario like the picture!). Let's take an example about that, imagine that I'm gonna to persist the sent message(Contact) by user in "ContactUs" of n-layered architecture web site (the same example I showed in StackOverflow).

This is my action to create the Contact:

  1. [HttpPost]
  2. public ActionResult Create(ContactViewModel contactViewModel)
  3. {
  4.     var request = new CreateContactRequest(contactViewModel);
  5.     _contactService.CreateContact(request);
  6.     return View();
  7. }

 

and about the service implementation, I've done like this:

  1. public CreateContactResponse CreateContact(CreateContactRequest request)
  2. {
  3.     var response = new CreateContactResponse();
  4.     var contact = request.ContactViewModel.ConvertToContactModel();
  5.     try
  6.     {
  7.         _contactRepository.Add(contact);
  8.         _unitOfWork.Commit();
  9.         response.Success = true;
  10.         response.MessageType = MessageType.Success;
  11.         response.Message = ServiceMessages.GeneralServiceSuccessMessageOnCreation;
  12.         _logger.Log(response.Message);
  13.     }
  14.     catch (Exception exception)
  15.     {
  16.         response.Success = false;
  17.         response.MessageType = MessageType.UnSuccess;
  18.         response.Message = ServiceMessages.GeneralServiceErrorMessageOnCreation;
  19.         _logger.Error(exception.Message);
  20.     }
  21.     return response;
  22. }

  

And  finally in repository layer, I have this generic Add method:

  1. public void Add(T entity)
  2. {
  3.     SessionFactory.GetCurrentSession().Save(entity);
  4. }
  5.  

As you can see there are lots scenario in this example such as converting ViewModel to Model, using request and response pattern in Service, injecting the interfaces,  adding to the repository, committing by UnitOfWork and blah blah. But you I can also do all of above with just a simple action method:

  1. [HttpPost]
  2. public ActionResult Create(Contact contact)
  3. {
  4.     SessionFactory.GetCurrentSession().Save(contact);
  5.     return View();
  6. }

 

You know the above implementation on an action is not the best solution when your application is complex and large scale, but if it is not try to use something like that as it's easy to develop and defiantly high performance.

Optimizing n-layered architectures is not easy task, But it is easy to change the content of any layer without making corresponding changes in other layers. It is more readable, maintainable, extensible, flexible, testable and is suitable for parallel development specially in team working but you know it has its own disadvantages.

If you have enough factors to break your application into layers, for example if you want to let other applications to access to your application via a service, separate your concerns;so apply to layered architecture but keep in mind that:

 

  1. This architecture leads to reduction of network traffic, faster network communications, greater reliability and greater overall performance.
  2. As layers usually live in separate assemblies so This results in high communications overhead.
  3. More layer cause more network and network bandwidth, process involved. 



Domain driven design VS model driven architecture

Domain Driven design(DDDesign) is not the same Model Driven Architecture(MDA). Although The root of both DDDesign and MDA is the same and it is Model Driven Engineering and also both of them aim to solve the problem of converting a 'pure' problem domain model into a full software system. But there are some differences.

Domain Driven Design concentrates on Modeling and solving the Domain problem by Capturing the model from Ubiquitous language. it is about modeling a domain of knowledge with a high level of abstraction and it's focuses are on domain logic and tries to keep the design as much close to the real world. In DDDesign you create the model with the Ubiquitous language so you should understand the business without any technical issues. In other side model forms the ubiquitous language of DDDesign which explains the domain in a simple form and it's kinda a backbone of DDDesign.

But Model driven architecture is an approach on building the model of the system. As I mentioned MDA is a kind of domain engineering too. A model is just some taken classes, methods and ... from the problem domain. MDA provides you to use multiple standards such UML. 

 

but you know it doesn't stop there, I don't know more than these two paragraphs about differences of DDD and MDA! please let me know more about these two architectures and differences by comments, thanks...



Most common architectures of enterprise applications

"An effective enterprise application should be divided into layers", An Enterprise application should has the flexibility, maintainability, scalability , testability and extensibility. And to achieve this there are some techniques and principles like Separation of concern in layers and components and loose coupling. And if you are developing a web application, in order to make it secure and accessible, you need to distribute the application over multiple physical tiers. To ensure high performance and reliability, the application must be testable. Now I'm going to describe some architectural contexts just notice that I'm just talking about different kinds of layers and tiers, and based on your solution and business you can apply each of them and you don’t need to have all of them in every enterprise application.

 

 

What is the layered architecture? 

Layering is mostly about allocating specific responsibilities for the software. Maybe you have heard about "tier" instead of layer, it's OK! But tire mostly used for representing physical layout it's a project in the solution (in .NET), but layer is not just a project in the solution although it could be. Layer is a conceptual element which could be consist of several tiers. So a tier could be a layer and vice versa but not in all the cases, in real world several tier could represent a layer. A Layer is completely separated from other layers and boundaries are supported by interface contracts. There are some Common layers that you can find in most of the enterprise application:  infrastructure layer, Domain Layer, Application layer, Service layer, Presentation layer

 

 

Infrastructure and crosscutting Layer

"The Infrastructure Layer contains the standards and best practice designs for the underlying platform components", which enable the adequate functioning of all other layers. Infrastructure contains some basic and common configuration for all of the layers in the project such as Domain Events, Validations, basic Helpers, Unit Of work and etc.  Maybe you have heard about crosscutting layer, you can merge it with infrastructure layer. You can put authentication, authorization, Email, Logging and service in crosscutting(if you  have separated it from infrastructure).

 

 

Domain Layer

Domain is the heart and hardest part of the software. Designing the correct Domain model could guarantee the software success. Domain is not just about some properties (domain objects) which represent fields of tables in the database. Complex business rules, behaviors should be solved in domain layer. If you would like to know more about Domain Layer, you should go to the world of Domain Driven Design!

 

 

Data Access Layer and Repository

As I mentioned here before, Data access layer is something different from repository, if you have business object in your domain then you can have data access layer but if you have Aggregate(DDDesign) you can have Repository layer. The data layer provides access to external systems such as databases. You can use Microsoft Entity framework or Non Microsoft open source ORM like Nhibernate in your DAL or Repository layer.

 

 

Services Layer

"The services layer defines the composite set of functions that are required to create a reliable, secure, and transacted service." A set of specifications define the standard operating behavior for the services and enables them to be aggregated or composed into other applications. An application exposes some of its functionality for using other services or frameworks by service interface. By dependency injection tools you can make it lose coupled. It's so common to separate service interfaces from service implementation in other layer.

 

 

Business Layer

"Large enterprise applications are often structured around the concepts of business processes and business components." The business layer implements the business functionality of the application. Business logic should be separate from the presentation.

 

 

Presentation Layer

The presentation layer provides the application's user interface. It could be any framework, for example in .NET it could be Asp.net MVC, Asp.net WebForm, Silverlight, WPF and so on. Presentation layer talks to service layer interfaces.

 

 

 

Related posts

  1. http://msdn.microsoft.com/en-us/library/ff650258.aspx
  2. http://www.cs.bgu.ac.il/~oosd051/uploads/classes/4-Layered-architectures.pdf
  3. http://msdn.microsoft.com/en-us/library/ee658109.aspx
  4. http://codeidol.com/community/java/what-is-a-layered-architecture/10833/
  5. http://msdn.microsoft.com/en-us/library/ff648105.aspx



Difference between Anemic Domain Model and Rich domain model

There are lots of differences between these to approach. Anemic model is an anti-pattern introduced by martin fowler to encourage developers to duplicate code!  Based on the main idea behind DDD, if you have ubiquitous language then you can have domain model Anemic domain model is the use of a software domain model where the domain objects contain little or no business logic. in a Rich Domain Model behavior is included in the domain object while in Anemic Domain Model behavior is implemented in separate classes.

At some point in the design of the software it is decided to implement certain pieces of logic for a domain entity outside of that domain entity.  This may be as a result of an explicit design decision or some pieces of logic just cannot be implemented in the domain entity because it is a persistent class and has no internal references to external services. 

The fundamental horror anemic model is that it's so contrary to the basic idea of object-oriented designing; which is to combine data and process them together. anemic objects are not real objects, and it's something different from object-oriented design. In anemic model, business logic is typically implemented in separate classes which transform the state of the domain objects. "A domain model in problem solving and of all the topics related to a certain problem. It describes the various entities, their attributes, roles, and relationships, plus the constraints that govern the problem domain. The domain model is created in order to represent the vocabulary and key concepts of the domain problem." ~ wikipedia



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?