Showing posts with label MVC. Show all posts
Showing posts with label MVC. Show all posts

Thursday, January 13, 2011

Doing DCI with ASP.NET MVC

The DCI - Data, Context, Interaction - paradigm (intro article, an earlier post) brings the roles domain objects play at runtime to center stage. DCI also fits right into the gaps of MVC. What? Which gaps?

MVC Gaps
Back in the day, when MVC was originally described by Trygve Reenskaug as an architecture approach it was all about the users mental model, giving the user the sense of just working directly with the domain objects. Now dont confuse this with the dreaded CRUDy forms-over-data battleship grey enterprise app. Those apps force the user to manipulate the data directly; respecting, fighting and being forced into submission by the techniocal details of databases. MVC on the other hands puts that the model is the users mental model - the programmer, then has to deal with hiding the technicalities of persistence and such. As illustrated below the users works as if manipulating the domain objects directly. The view simply reflects the model state, the controller reacts to user actions, and translates them to model updates, and that's it.
Direct manipulation metphor as illustrated by Trygve Reenskaug
This is fantastic for fairly simple apps. But as soon we introduce business rules with a certain amount of complexity, the direct manipulation metaphor does not suffice anymore. We need somewhere to put those business rules.  -The controller already has clear responsibility, so in keeping with single responsibility principle that's not the place for the behaviour. -The traditional OO answer is to put the behaviour into the model, but that leads to hard-to-follow logic jumping back and forth in the model objects, and (gark) up and down long inheritance chains. Moreover it turns out that a given domain object will play different roles over times. I.e. the object doesn't need just one behaviour, it needs several, and even worse it needs different behaviours over time. There goes SRP again, only this time in the "intelligent model".

Roles and  Contexts to Fill the Gap
So we need something more than MVC: The view is not the place for the behaviour, the model is not the place for the bahivour, and the controller is not the place for it either. This is where roles as separate things come into play. We want explicit roles. We want those business rules implemented in the roles. And we want to assing those roles to domain objects as needed.

The role a given object plays at a given moment depends on the context at that moment. So why not introduce contexts as something explict along with the explicit roles? Together roles implementing behaviour and contexts assigning roles to objects fill the gap in MVC.

Back to APS.NET MVC
Lets get practical: Where do the contexts and the roles go then? Since the contexts manage assigning roles and kicking off the behaviuour the contexts and roles fit well together. In the ASP.NET MVC + DCI demo I did for ANUG I organized the code like this:

 The Contexts folder has a subfolder for the use case I demoed. Other use cases would have their own subfolders. Inside the subfolder is the context for executing that use case, and the associated roles.

What is a role in C#? A role in C# is a set of extension methods on an interface (see this and that for more on roles in C#):

    1     public static class TransferMoneySourceTrait
    2     {
    3         public static void TransferTo(this TransferMoneySource self, TransferMoneySink recipient, decimal amount)
    4         {
    5             // The implementation of the use case
    6             if (self.Balance < amount)
    7             {
    8                 throw new ApplicationException(
    9                     "insufficient funds");
   10             }
   11 
   12             self.Withdraw(amount);
   13             self.Log("Withdrawing " + amount);
   14             recipient.Deposit(amount);
   15             recipient.Log("Depositing " + amount);
   16         }
   17     }

How does the context track the role assignments? Simple:

    8     public class TransferMoneyContext
    9     {
   10         public TransferMoneySource Source { get; private set; }
   11         public TransferMoneySink Sink { get; private set; }
   12         public decimal Amount { get; private set; }
   13 
   14         public TransferMoneyContext(TransferMoneySource source, TransferMoneySink sink, decimal amount)
   15         {
   16             Source = source;
   17             Sink = sink;
   18             Amount = amount;
   19         }
   20 
   21         public void Execute()
   22         {
   23             Source.TransferTo(Sink, Amount);
   24         }
   25     }
   26 

Where are the objects mapped to roles? Right in the seam between the controller and the context (lines 35 to 37):

   11     public class TransferMoneyController : Controller
   12     {
   13         AccountRepository accountRepo = new AccountRepository();
   14 
   15         public ActionResult Index()
   16         {
   17 
   18             ViewData["SourceAccounts"] =
   19                 accountRepo.Accounts.Select(a => new SelectListItem {Text = a.Name, Value = a.Id.ToString()});
   20             ViewData["DestinationAccounts"] =
   21                 accountRepo.Accounts.Select(a => new SelectListItem {Text = a.Name, Value = a.Id.ToString()});
   22             return View();
   23         }
   24 
   25         [AcceptVerbs(HttpVerbs.Post)]
   26         public ActionResult Index(FormCollection form)
   27         {
   28             var sourceAccountId = form["SourceAccounts"];
   29             var destinationAccountId = form["DestinationAccounts"];
   30             var amount = form["Amount"];
   31 
   32             var sourceAccount = accountRepo.GetById(int.Parse(sourceAccountId));
   33             var destinationAccount = accountRepo.GetById(int.Parse(destinationAccountId));
   34 
   35             new TransferMoneyContext(sourceAccount as TransferMoneySource,
   36                 destinationAccount as TransferMoneySink,
   37                 decimal.Parse(amount)).Execute();
   38 
   39             ViewData["Amount"] = amount;
   40             ViewData["Source"] = sourceAccount.Name;
   41             ViewData["Destination"] = destinationAccount.Name;
   42 
   43             return View("Result");
   44         }
   45     }

Apart from lines 35 to 37 this is all just standard ASP.NET MVC stuff: Getting data in and out of the ViewData, and returning the view to render back to the user.

Summing Up
MVC is great for simple situations. It doesn't quite scale to complex business scenarios, but DCI does, and the two are a great match.
Leveraging the power of C# to do DCI and the niceness of ASP.NET MVC to go along with it, makes for a - IMHO -very compelling architecte style for an enterprisy web app.

Tuesday, June 9, 2009

Exploring a WPF Business Application Architecture 1

I've been spending some time looking into how to easily build WPF based line-of-business applications lately. To illustrate my thoughts on that subject I'll put together a sample based on the time honored Java Pet store. In this post I'll write a bit about the type of application I'm aiming for, the pet shop, and the architecture I'm aiming for. In a series of following posts I'll show how the domain model, the persistence, the presentation and so on are coded.

So, I'm not trying to figure out how every WPF app should be architected. Far from it. I'm trying to figure out a default architecture for moderately sized business applications. I.e. apps that: Use WPF for presentation, use an SQL Server database for persistence, runs on an intranet, has in the order 100 - 200 unique users, has moderate to large amounts of data (not huge, though), and no special security issues.

To illustrate I'll use a pet shop: The users can browse through categories of pets, put them in their shopping cart, and eventually check out and pay for the pets.

The plan is to use the MVVM pattern which is a variation on MVC, that focuses on allowing for use of WPF's 2-way data binding while still allowing for separation of concerns. The domain model is nicely separated from the view by the view model, which adapts the data in the domain model to the needs of the view. The presentation logic is pulled out of the code behind files to keep it separated from the view itself. All-in-all MVVM delivers a nice structure that allows for good testability and maintainability. To implement this part I might use Caliburn or PRISM or I might do it by hand. I haven't decided yet.
For the persistence of the domain model to the database I'll use Castle.ActiveRecord which is build around Fowler's Active Record pattern: Each domain object is responsible for its own persistence. Each domain class maps to a database table and has CRUD operations. Each domain object corresponds to a database row. Castle.ActiveRecord makes it really easy to use the Active Record pattern: You just have to add a few attributes to the domain classes and their persisted fields and off you go. Your domain objects are still POCOs except for the attributes, so you get to keep your domain object clean and almost-free of infrastructure.
Lastly I plan to throw in Castle.Windsor for dependency injection.

That's it for now. Next post will be about the pet shop's domain model, and about persisting it through ActiveRecord.

Monday, May 4, 2009

DCI in C#

The DCI, or the Data Context and Interaction is an approach to implementing domain logic and use cases in terms of the roles domain objects play at runtime. It is being developed and promoted by Trygve Reenskaug and James O. Coplien, who have written a very good introductory article about DCI at Artima.com. Here I'll stick to a very brief explanation and then jump into implementation of DCI in C#.

DCI at a Glance

I find that the DCI design is most easily understood in the context of Model View Controller. MVC, in its purest form, allows the end user to reach through the view, via the controller into the model and manipulate it directly. This is fine as longs the user is actually able to perform his tasks simply by massaging the domain objects. As soon as the application needs to support some sort of coordinated sequence of actions that the user is not allowed to control on his own,  something more is needed. Where is that control coded? Is it in the controller? Is it spread out between a number of domain classes? Is it in a business or service layer on top on the domain model? -DCI offers a different take:
DCI tells us to think in terms of three main concepts: The data captured in the domain model, the interactions between domain objects happening at runtime and the context in which the interactions happen. DCI also tells us to implement interaction in terms of roles: Domain objects take on different roles throughout the execution of an application. The interactions between domain objects happen in terms of these roles. The context of an interaction is the collection of runtime objects that will take part in the interaction, each referenced by role. The nice thing is that those coordinated sequences of actions are implemented directly in the role that will plays the lead part in the interaction. The context will provide the role with all the collaborators it needs. 
Right, enough explanation, the article mentioned above does a better job at explaning DCI anyway, so I'll just jump right into the C# code.

The C# Code

I'll walk through how the data, the context, and the role can be implemented in C#. To do this I'll use a simplistic banking example and implement a simplified money transfer use case in the role TranferMoneySource. The example is the same as the one used in the article linked above.
The domain model (i..e the D in DCI) consists of a savings account and an abstract account:

public abstract class Account
{
   public double Balance { get; protected set; }

   public void Withdraw(double amount)
   {
       Balance -= amount;
   }

   public void Deposit(double amount)
   {
       Balance += amount;
   }

   public void Log(string message)
   {
       Console.WriteLine(message);
   }
}

public class SavingsAccount 
    : Account, TransferMoneySource, TransferMoneySink
{
    public SavingsAccount()
    {
        Balance = 1000;
    }

    public override string ToString()
    {
        return "Balance " + Balance;
    }
}

The TransferMoneySource and TransferMoneySink are roles, and I'll get back to those. For now just notice that the roles must be interfaces, since the single inheritance of C# is used to extend the abstract Account.
The context (the C) in which the money tranfer use case is executed is the TransferMoneyContext:

public class TransferMoneyContext
{
    public TransferMoneySource Source { get; private set; }
    public TransferMoneySink Sink { get; private set; }
    public double Amount { get; private set; }

    public TransferMoneyContext(TransferMoneySource source,
        TransferMoneySink sink, double amount)
    {
        Source = source;
        Sink = sink;
        Amount = amount;
    }

    public void Execute()
    {
        Source.TransferTo(Sink, Amount);
    }
}

The context captures the objects necesarry to execute the money transfer use case in terms of the roles they play in that use case. I.e. the context captures the account that acts as source and the account that acts as sink. The context just holds on to these object until the Execute method is called. At that point the control is transferred to the role capable of running the use case - the source account.

Lastly the role implementation remains. The use case (the I) is captured in the role, and the role is attached to any number of domain objects.  As mentioned above the roles are interfaces, but they also need to implement the use case. This is achieved through extension methods attached to the role interfaces. This enables us to tie behaviour to interfaces, which is what we need in order to tie the use case implementation to the role, which in turn can be tied to any domain object. The roles are implemented like this:

 public interface TransferMoneySink
{
    void Deposit(double amount);
    void Log(string message);
}

public interface TransferMoneySource
{
    double Balance { get; }
    void Withdraw(double amount);
    void Log(string message);
}

public static class TransferMoneySourceTrait
{
    public static void TransferTo(
        this TransferMoneySource self,
        TransferMoneySink recipient, double amount)
    {
        // The implementation of the use case
        if (self.Balance <>
        {
            throw new ApplicationException(
                "insufficient funds");
        }

        self.Withdraw(amount);
        self.Log("Withdrawing " + amount);
        recipient.Deposit(amount);
        recipient.Log("Depositing " + amount);
  }
}

In essence the above usage of extension methods on interfaces emulates traits in C#.

DCI on .NET

While this offers one way of doing DCI on the .NET platform it is not the only way. There are also implementation in Python and Ruby. Attaching roles to objects is somewhat more straight forward in Ruby, where it is done by mixing a module specifying the a role into a domain object at runtime. With IronRuby maturing nicely, that could easily turn out to be the nicer DCI implementation for .NET.