Posts in English
Renewing DDDSample.Net, iteration 0
Sep 27th
As I promised in one of the previous posts, I am now in process of renewing the DDDSample.Net source code. It’s been quite a while since I published the first version of it. Many technologies have changed and my take on Domain-Driven Design and software architecture also has changed slightly.
First of all, the repo was moved to github. Hurray! In the process of transforming TFS repository into a git one I lost the branch structure. Originally all versions were branched one from another which made updating all samples a little bit easier since (ideally) I had to change only one and then merge this change. With git I am thinking of a slightly different structure. I am pretty sure I can freeze some portions of the solution (like routing engine and most of the UI) and move them to separate repos. Then I can import them as submodules to each of the samples.
At first I just wanted to add new features to the existing samples but when I opened the vanilla version (a port of Java DDDSample) I found out that it is so outdated that it urgently needs to be renewed. The changes I made so far include:
- Upgrading solution to VS2010 format
- Removing the web setup project (I guess nobody used it, ever)
- Switching to NuGet for resolving most of the packages (using don’t commit packages workflow described here by David Ebbo)
- Upgrading some dependencies (like NHibernate) to the newest versions
- Switching from using façade-like classes in application layer to commands and command handlers implemented using brand new tiny LeanCommandUnframework (a separate micro project hosted here on github)
- Switching from Unity 1.2 to Autofac
- Removing dependency on NServiceBus
- Cleaning up the global.asax file
I am now quite happy with the solution. Everything seems to have its place in the architecture. There are some things yet to be clean up such as changing the way command handlers are created but these should be minor fixes. If you have some spare time, please clone the repo and check if you like what I did. And please note that only Vanilla version was updated.
Supporting Inversion of Control
Sep 22nd
As you know, I am a big supporter of Inversion of Control. Fortunately the discussion whether to use IoC (and a container) or not is over. We won, period. But this post will be about other type of support.
Because of IoC becoming so ubiquitous, statements like these
Our framework has very good support for IoC
Adding support for IoC is the goal of the next release
We support Inversion of Control containers such as Autofac, Windsor, Unity…
are becoming more popular on project blogs and roadmaps. Recently, ASP.NET has been guilty of this sin. I admit I was guilty too. What’s the problem you ask? The answer is simple. Inversion of Control does not need any support from your frameworks. Adding it does not solve any problem while it introduces a ton of new ones.
So-called support for IoC manifests itself in baking some abstraction of either Service Locator or whole container into the particular framework. Then you have ’satellite’ assemblies that implement this abstraction based on particular container. One of the problems is, the satellites have to be updated every time the container they depend on gets updated. If the container uses strong naming, it makes things even worse. Also, someone has to build all these implementations. Usually the author of the project builds one or two (for his favourite containers) and leaves the task to implement other to the community (you).
Some people may say that they need an IoC container in their framework because it is so damn complex that they cannot live without it. First of all, I think this is a code smell that suggest something is wrong with the design of the framework. But if you insist on not redesigning but using IoC instead, please ilmerge and internalize the container. I don’t want to see it. The most weird realization of this concept of using IoC container in the internals of the framework I’ve ever seen caused that nice, fluent, configuration API instead of configuring the framework directly, was putting things into the container so that they could be retrieved later.
The problem that people who introduce IoC support into their framework are trying to solve is the creation of your (application developer’s) components inside the framework. The idea of framework is, you pass some code to it and it will call it whenever it needs it. In languages such as C# it often means passing some type objects to the framework which are to be used to create instances later on. If you embrace IoC in your application (and as I said in the preface, I strongly believe you should do so) you expect dependencies to be injected to your components. But how can framework inject dependencies? It has to use the same container as you are using in the rest of the application. But instead of building huge abstractions over containers and trying to implement them, how about defining something as simple as this
public interface IObjectFactory
{
object GetInstance(Type instanceType);
void ReleaseInstance(object instance);
}
Implementation of this class would be trivial for any major container on the market so framework author does not need to put it into his framework (as ’satellites’). He can happily leave it for application developer to implement using his own container or maybe even Poor Man’s DI.
So, dear reader, please support the idea of Inversion of Control (by blogging, speaking etc.) but don’t add support for it in your pet framework. It would hurt both you and me.
The handler pattern
Sep 13th
Today I want to tell you about a pattern I see more and more frequently in my codebases. It is not a pattern in the sense of Gang of Four book. At least I haven’t thought about it in terms of a design pattern. It’s just a piece of code that shows here and there in slightly different versions. Let’s call it ‘handler’ because I can’t come up with a better name.
The idea is to have a set of classes that do something, whatever, and a class (façade) that allows you to execute all these classes for a given set of arguments. The classes that do something declare their capability of doing it by implementing a generic interface such as this one
public interface IHandler<in T>
{
void Handle(T argument);
}
In various versions the Handle can have various arguments. This example is the simplest one. In my current project I used this pattern to implement at least 4 concepts:
- service request validators (instead of Handle, there is a Validate method)
- service filters (with two methods, namely BeforeProcessing and AfterProcessing)
- request handlers (these look exactly the same as the example)
- event handlers
It may be the case that if you have a hammer, everything looks like a nail, but I find this pattern extremely useful. Because of that, I want to share with you a simple reference implementation of it. I know it’s neither optimal nor very clean but it can give you some ideas and you can make it better. Unfortunately I can’t share the original code because of copyright issues.
public class Handlers
{
private readonly IEnumerable<Type> _handlerTypes;
public Handlers(params Type[] handlerTypes)
{
_handlerTypes = handlerTypes;
}
public void Handle(object argument)
{
var matchingHandlerTypes = FindMatchingHandlerTypes(argument.GetType());
var handlers = matchingHandlerTypes.Select(CreateHandlerInstance);
dynamic dynamicArgument = argument;
foreach (dynamic handler in handlers)
{
handler.Handle(dynamicArgument);
}
}
private IEnumerable<Type> FindMatchingHandlerTypes(Type argumentType)
{
return _handlerTypes.Where(x => ImplementsHandlerOf(x, argumentType));
}
private static bool ImplementsHandlerOf(Type candicateHandlerType, Type argumentType)
{
return candicateHandlerType.GetInterfaces().Any(x => IsHandlerOf(x, argumentType));
}
private static bool IsHandlerOf(Type interfaceType, Type argumentType)
{
return interfaceType.IsGenericType
&& interfaceType.GetGenericTypeDefinition() == typeof (IHandler<>)
&& IsMatch(interfaceType.GetGenericArguments()[0], argumentType);
}
private static bool IsMatch(Type handlerInterfaceGenericArgument, Type argumentType)
{
return IsExactMatch(argumentType, handlerInterfaceGenericArgument)
|| IsInheritanceMatch(argumentType, handlerInterfaceGenericArgument);
}
private static bool IsInheritanceMatch(Type argumentType, Type handlerInterfaceGenericArgument)
{
return argumentType.IsSubclassOf(handlerInterfaceGenericArgument);
}
private static bool IsExactMatch(Type argumentType, Type handlerInterfaceGenericArgument)
{
return argumentType == handlerInterfaceGenericArgument;
}
private static object CreateHandlerInstance(Type handlerType)
{
return Activator.CreateInstance(handlerType);
}
}
Three things worth notice here are
- I really, really like functional programming with LINQ
- You can (and should) integrate your version with your favourite Inversion of Control container instead of using Activator.CreaterInstance
- Dynamic feature of C# is used as a replacement of some ugly wrapper classes and/or reflection. It can be easily rewritten in a way it compiles with C# 3.0.
Happy handling!
.NET architecture samples
Sep 8th
A Domain-Driven Design sample I created some time ago, DDDSample.Net, is now a little bit rusty. I though it is a good idea to spend some time and make it up to date. It will involve, for sure, moving the project to github because you all know what I thing about TFS version control.
Currently there are 4 major versions of DDDSample solution
- Vanilla (‘by the book’)
- CQRS with two relational databases
- CQRS with event sourcing
- Layered model
I am thinking about dropping the second one as it was more like an experiment, not a final solution. The layered model is an advanced version of vanilla solution witch demonstrates how to structure larger domain models. Another thing I might do is migrate the event sourcing sample to NCQRS. Or maybe I should use EventStore directly? What do you think?
Now the important part. I have some ideas what to implement next and I need your feedback. Help me rate them
- Event driven SOA a’la Udi Dahan. This would be probably an extended version of layered model sample but with slightly different structuring approach (autonomous services instead of layers).
- Vanilla with RavenDB as a data store
- Native CQRS with event sourcing on RavenDB according to this description by Ayende.
If you have some other ideas, post them in the comments. I am also thinking about getting rid of the installer projects. It does not make sense to just install the application in IIS and don’t look at the code. And if you open it, you can run it by hitting F5.
Domain-Driven Design by the book
Sep 6th
Starting a new project is fun. You (assuming you, reader, are The Architect) can make all the decision and do it right. You can use all the newest technologies you can find. And what do you do when it comes to designing business logic? Hopefully you base you decision on the level of complexity of the problem you are solving. If the problem is relatively easy, you implement a CRUD solution, right? On the other hand, if it looks really complex, you can enjoy having a good reason for CQRS architecture. But what’s between these two extremes? Enter (again) classic Domain-Driven Design by the book. I understand that in this CQRS noise you could forgot about this option. Let me remind you about architectural properties of such design.
10.000 feet view
The best way to describe such system is to use Jeffrey Palermo’s Onion Architecture approach. Domain model is the most inner layer of the onion. It contains your business logic and does not depend on anything significant (like WCF or NHibernate). The next layer of the onion would be something I usually call Application Layer. Notice that I skipped Domain Services Layer. It was intentionally. I consider domain services (if you really, really need to have them) part of the domain model. Application Layer is where your commands and command handlers live. For each business action there is a pair of a command and it’s handler. Trust me, making business operations explicit by implementing them as classes (as opposed to methods on a class/interface) pays off in the long run. If the application has a user interface, it is the outermost layer of the onion. If not, the Application Layer becomes the outermost one with it’s commands exposed via some remote interface (like WCF or NServiceBus).
Repositories and data access
You probably know I am a fan of repositories. I like the explicitness of their interface. In the architecture we are talking about you would probably use some kind of ORM (like my favourite NHibernate) so repositories would end up being a thin wrapper around the almighty mapper library. Using an ORM also implies that you have a Unit of Work in your solution. Most (probably all) of the major mappers have it implemented so it does not make any sense to not use it or write your own implementation.
Aggregate boundaries
The corollary of having a unit of work is the possibility of violating the aggregate boundaries. It needs discipline (and you, as The Architect, are the one who is responsible for maintaining it) to avoid transactions spanning multiple aggregates. Why is it so important? Because Aggregate Roots are usually used as concurrency units. Involving two concurrency units in a transactions can lead to all sorts of nasty things, including race conditions and deadlocks. There is one exception to this One Transaction-One Aggregate rule, namely creating new aggregates. Because newly created aggregates, for obvious reasons, can’t be involved in two transactions (thus causing concurrency problems), you can create them as part of a transaction initiated for another, already existing, aggregate.
Of course, you can read as much as you like, also from other aggregates.
Testability
There are several things you can test in such solution, each of which requires a different strategy. First of all you should test your domain model as it is your most valuable asset. You can read more about it in one of the previous posts. For testability reasons you should strive to squeeze as much business logic in Value Objects as you can. The remaining logic will be placed on the entities.
Another thing worth testing is persistence. You have to prove that you can persist and load objects in any valid state. Because it would be not practical to test for all the valid states, I would recommend testing for the most complex states. Odds are that simpler states will just work.
Application layer tests are also worth the effort. They come in two flavours: with mocked repositories and with real repositories. It depends on particular case which one is more useful. Testing with real repositories requires of course some database. The easiest ones to use in test environment are SQLite and SQL Server CE.
Last but not least, there is usually some UI code (like controllers) to be tested. Don’t forget about it.
Events
Yes, the events have their place also in this architecture. We need them because they are the ultimate integration mechanism. You can do all sorts of cool things if your system publishes the changes to its internal state as a serious of events. If you don’t believe me, read or listen to Udi Dahan when he talks about SOA done right.
You can implement events in a classic DDD solution in two ways. Either make them a separate concept like in this article of Udi or make them part of your domain model (as proposed by Eric Evans in one of his great presentations). I consider the latter approach cleaner but more difficult to implement properly. The choice is yours.
User interface
Some systems really need a user interface. Really. From time to time it is good to display something to the user and let him make some decisions. It makes users feel important etc. So how do you get the data out of the store so that use can see it? As you may have read before on this blog, I am a big opponent of using repositories for getting the data to the views. This is a separate responsibility which I like to implement in Finder classes. Another issue is, how you implement these finders. As usual, you have more than one option. One is to have a set of classes parallel to your domain model that are mapped to the same tables in the database. Of course you would also need another set of ORM mappings. You can read more about this approach here. Another, also valid, approach would be to map domain model classes to DTOs using a tool such as AutoMapper. I hear you saying that mapping domain objects to DTOs is considered an anti pattern. I guess I have said it a few times. But what I am proposing here is a bit different. You should encapsulate the way you get your DTOs in the finders so that it’s not an architectural issue any more. If it’s not an architectural issue, it can’t be an anti-pattern, right? You may have some finders that issue a plain old SQL, some that map from domain objects and some that use database-mapped DTOs. Use whatever method works best to solve the problem at hand and don’t forget to encapsulate the solution.
Summary
I would like to hear from you what do you think about this architecture. For sure it’s not the ideal one, the one you dream about. But I’ve implemented it a few times and it worked reasonably well. Do you have any ideas how can I improve it without introducing additional complexity?



