Leveraging DI with Command Pattern (C# / MVC)

When building an application using MVC framework, one of the challenges is scalability. When the application starts to grow, in most cases it would crowd the Controller. The controller would become a massive pool of business logic with codes no less than 100 lines per methods.

One of the solutions to such problem is the usage of command handler pattern. This is based on the Command-Query separation principle. For the command handler pattern, each request to do a write would be encapsulated into a command accompanied with a particular handler to execute.

Before digging deeper into this pattern, here are few gotchas that I found when using this pattern, and why this pattern may not for you:

  1. God Command Object (see more God Object). This pattern helps to create command and use them fairly easily and simple.  Aim to create small command objects and with high visibility. Model your command object and restrict their usage.
  2. Lots of objects. As oppose to just passing parameters into the controller, this pattern requires an object to be created for the parameters. When we starts to have large pool of commands, they may become difficult to manage and navigate.  Have a ‘Map’ (UML diagram, whatever you call this) to help navigate through your commands.
  3. CRUD only application could already leverage on .NET MVC model binding. This especially when the UI is a flat UI form as oppose to workflow UI that may have multiple ajax to update an entity. Use this pattern only when you have more business rules that may apply, or when you feel that parts of the application starts to grow more than you can manage.
  4. The usage of the pattern will not solve the business and boundary issues. It will help to implement and separates their concern and to create SOLID application. For more information on modelling the business with their concerns, take a look at DDD bounded context.

Using command pattern also means:

  1. Separating logic / controller process into different area. As a result of this, the controller will be very thin, and easily manage. The logic / controller process resides somewhere else in the code. For a large model, this could very well be it’s own project with its own service.
  2. Easier way to manage and navigating through the business logic and identifying errors. As we separate the concerns of logic to a different place, this in turns allows flexibility across areas in the application.
  3. Confidently able to change things without side effects.
  4. When extended, command object can leverage decorator pattern to have logging or other extension. This allow visibility across all commands, their input and their result. The value of this is the visibility on user actions. This allow us to analyse user interaction into the UI of the application. (out of context of this article).
  5. Although this particular example is for the Controller, this pattern is generic enough for other places as well, such as service layer.

One of the challenges creating a handler for commands is the requirement for the handler itself. Each command could contain a simple, or many dependencies. It could require a call to a service, or multiple services in order to invoke the command. This is where we could leverage dependency injection (e.g Unity) with the service locator pattern (although in this case, we would locate the command handler). We use Unity in this example to help us with the dependencies that each handler needs.

Let’s instantiate our interface for both command, and command handler.

public interface ICommand {
    bool IsValid(); // poor man’s validation
}

And our object for the command:

public class UpdateAddressCommand : ICommand
{
    public string Street { get; set; }
    public string Unit { get; set; }
    public string Number { get; set; }
    public string Suburb { get; set; }
    public string Postcode { get; set; }
    public bool IsValid() {
        // poor man’s validation
        return true;
    }
}

In here, we want to have public get and setter. This will be the object being passed on into our Controller.

Let’s instantiate our handler.

public interface ICommandHandler<ICommand> {
    bool Handle(ICommand command);
}

In this example, our command handler requires an IAddressService and IAddressGoogleMapService. The handler requires both services in order to process the UpdateAddressCommand. In here, we leverage Unity to help us instantiating the command handler, and hence our command handler would look like:

public class UpdateAddressCommandHandler : ICommandHandler<UpdateAddressCommand> {
    private readonly IAddressService _addressService;
    private readonly IAddressGoogleMapService _gMapService;

    public UpdateAddressCommandHandler(IAddressService addressService, IAddressGoogleMapService gMapService) {
        _addressService = addressService;
        _gMapService = gMapService;
    }    

    public Handle(UpdateAddressCommand command) {
        if (!command.IsValid()) return false;
        // processing command…
        return true;
    }
}

Our method in Controller then becomes:

public AddressController : Controller {
    private readonly ICommandHandlerLocator _locator;   

    public AddressController(ICommandHandlerLocator locator) { … }
    public ActionResult UpdateCustomerAddress(UpdateAddressCommand command) {
        If (_locator.Handle(command)) return View(“success.cshtml”);
        return View(“failed.cshtml”);
    }
}

 

Where to from here

From the above example, simple DI and command pattern can help to manage the process and creates better separation for the logic or processes. The above example could be modified further for queries and hence creating a proper command and query separation for your application. They may also requires to be modify according to the need of the application itself.

Related Posts:
Generic Interfaces with Unity

Like this article or have a question? Post a comment below!

1 thought on “Leveraging DI with Command Pattern (C# / MVC)

  1. Pingback: DRY-ing code with Command Handler | Code Construct

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s