Applying Domain-driven Design and Patterns

Jimmy Nilsson

Mentioned 29

A practical guide to applying patterns in building a customized architecture for the application you are developing.

More on

Mentioned in questions and answers.

I'am unclear as to what the roles and responsibility of the factory class is. I know enough that the factory class should be resposible for the creation of domain objects (aggregate root) along with its associated entities and value objects.

But what is not clear to me is where the factory "layer" lies with a DDD architecture? Should the factory be calling directly into the repository to get its data or the service library?

Where does the factory fit into the following framework:
UI > App > Domain > Service > Data

Also, because the factory is the only place allowed for object creation would'nt you get circular references if you wanted to create your objects in your data and service layers?

If the role of the factory class is for object creation then what benefits does the service layer have?

I've asked a lot of questions and appreciate any response. What i'am lacking is a sample application which demonstrates how all the layers in a domain driven design project come together...Is there anything out there?

But what is not clear to me is where the factory "layer" lies with a DDD architecture? Should the factory be calling directly into the repository to get its data or the service library?

The factory should be the one-stop shop to construct domain objects. Any other part of the code that needs to do this should use the factory.

Typically, there are at least three sources of data that are used as input into a factory for domain object construction: input from the UI, the results of queries from persistence, and domain-meaningful requests. So to answer your specific question, the repository would use the factory.

Here is an example. I am using Holub's Builder pattern here. Edit: disregard the use of this pattern. I've started realizing that it doesn't mix too well with DDD factories.

// domain layer
class Order
    private Integer ID;
    private Customer owner;
    private List<Product> ordered;

    // can't be null, needs complicated rules to initialize
    private Product featured; 

    // can't be null, needs complicated rules to initialize, not part of Order aggregate
    private Itinerary schedule; 

    void importFrom(Importer importer) { ... }

    void exportTo(Exporter exporter) { ... }

    ... insert business logic methods here ...

    interface Importer
        Integer importID();
        Customer importOwner();
        Product importOrdered();

    interface Exporter
        void exportID(Integer id);
        void exportOwner(Customer owner);
        void exportOrdered(Product ordered);

// domain layer
interface OrderEntryScreenExport { ... }

// UI
class UIScreen
    public UIScreen(OrderEntryDTO dto) { ... }

// App Layer
class OrderEntryDTO implements OrderEntryScreenExport { ... }

Here is what the OrderFactory might look like:

interface OrderFactory
    Order createWith(Customer owner, Product ordered);
    Order createFrom(OrderEntryScreenExport to);
    Order createFrom(List<String> resultSets);

The logic for the featured Product and the generation of the Itinerary go in the OrderFactory.

Now here is how the factory might be used in each instance.

In OrderRepository:

public List<Order> findAllMatching(Criteria someCriteria)
    ResultSet rcds = this.db.execFindOrdersQueryWith(someCriteria.toString());
    List<List<String>> results = convertToStringList(rcds);

    List<Order> returnList = new ArrayList<Order>();

    for(List<String> row : results)

    return returnList;

In your application layer:

public void submitOrder(OrderEntryDTO dto)
    Order toBeSubmitted = this.orderFactory.createFrom(dto);


    // do other stuff, raise events, etc

Within your domain layer, a unit test perhaps:

Customer carl = customerRepo.findByName("Carl");
List<Product> weapons = productRepo.findAllByName("Ruger P-95 9mm");
Order weaponsForCarl = orderFactory.createWith(carl, weapons);;


Where does the factory fit into the following framework: UI > App > Domain > Service > Data


Also, because the factory is the only place allowed for object creation would'nt you get circular references if you wanted to create your objects in your data and service layers?

In my example, all dependencies flow from top to bottom. I used the Dependency Inversion Principle (PDF link) to avoid the problem you speak of.

If the role of the factory class is for object creation then what benefits does the service layer have?

When you have logic that doesn't fit into any single domain object OR you have an algorithm that involves orchestrating multiple domain objects, use a service. The service would encapsulate any logic that doesn't fit in anything else and delegate to domain objects where it does fit.

In the example I scribbled here, I imagine that coming up with an Itinerary for the Order would involve multiple domain objects. The OrderFactory could delegate to such a service.

BTW, the hierarchy you described should probably be UI > App > Domain Services > Domain > Infrastructure (Data)

I've asked a lot of questions and appreciate any response. What i'am lacking is a sample application which demonstrates how all the layers in a domain driven design project come together...Is there anything out there?

Applying Domain Driven Design and Patterns by Jimmy Nilsson is a great compliment to Eric Evans' Domain-Driven Design. It has lots of code examples, though I don't know if there is an emphasis on layering. Layering can be tricky and is almost a topic separate from DDD.

In the Evans book, there is a very small example of layering you might want to check out. Layering is an enterprise pattern, and Martin Fowler wrote Patterns of Enterprise Application Architecture, which you might find useful too.

I'm trying to understand the concepts behind DDD, but I find it hard to understand just by reading books as they tend to discuss the topic in a rather abstract way. I would like to see some good implementations of DDD in code, preferably in C#.

Are there any good examples of projects practicing DDD in the open source world?

A good read is Jimmi Nilssons book (and blog for that matter) Applying domain driven design

It's a mixture of Evans and Fowlers books (Domain-Driven Design - Evans), and (Patterns of Enterprise Application Architecture - Fowler)

Code Camp Server, Jeffrey Palermo's sample code for the book ASP.NET MVC in Action is open source and uses DDD.

(Same as my answer in Good Domain Driven Design samples)

I've seen a trend to move business logic out of the data access layer (stored procedures, LINQ, etc.) and into a business logic component layer (like C# objects).

Is this considered the "right" way to do things these days? If so, does this mean that some database developer positions may be eliminated in favor of more middle-tier coding positions? (i.e. more c# code rather than more long stored procedures.)

If the applications is small with a short lifetime, then it's not worth putting time into abstracting the concerns in layers. In larger, long lived applications your logic/business rules should not be coupled to the data access. It creates a maintenance nightmare as the application grows.

Moving concerns to a common layer or also known as Separation of concerns, has been around for a while:


The term separation of concerns was probably coined by Edsger W. Dijkstra in his 1974 paper "On the role of scientific thought"1.

For Application Architecture a great book to start with is Domain Driven Design. Eric Evans breaks down the different layers of the application in detail. He also discusses the database impedance and what he calls a "Bounded Context"

Bounded Context

A blog is a system that displays posts from newest to oldest so that people can comment on. Some would view this as one system, or one "Bounded Context." If you subscribe to DDD, one would say there are two systems or two "Bounded Contexts" in a blog: A commenting system and a publication system. DDD argues that each system is independent (of course there will be interaction between the two) and should be modeled as such. DDD gives concrete guidance on how to separate the concerns into the appropriate layers.

Other resources that might interest you:

Until I had a chance to experience The Big Ball of Mud or Spaghetti Code I had a hard time understanding why Application Architecture was so important...

The right way to do things will always to be dependent on the size, availability requirements and lifespan of your application. To use stored procs or not to use stored procs... Tools such as nHibrnate and Linq to SQL are great for small to mid-size projects. To make myself clear, I've never used nHibranate or Linq To Sql on a large application, but my gut feeling is an application will reach a size where optimizations will need to be done on the database server via views, Stored Procedures.. etc to keep the application performant. To do this work Developers with both Development and Database skills will be needed.

DDD states that you should only ever access entities through their aggregate root. So say for instance that you have an aggregate root X which potentially has a lot of child Y entities. Now, for some scenario, you only really care about a subset of these Y entities at a time (maybe you're displaying them in a paged list or whatever).

Is it OK to implement a repository then, so that in such scenarios it returns an incomplete aggregate? Ie. an X object who'se Ys collection only contains the Y instances we're interested in and not all of them? This could for instance cause methods on X which perform some calculation involving the Ys to not behave as expected.

Is this perhaps an indication that the Y entity in question should be considered promoted to an aggregate root?

My current idea (in C#) is to leverage the delayed execution of LINQ, so that my X object has an IQueryable to represent its relationship with Y. This way, I can have transparent lazy loading with filtering... But getting this to work with an ORM (Linq to Sql in my case) might be a bit tricky.

Any other clever ideas?

Jimmy Nilsson hints in his book that instead of reading a complete aggregate you can read a snapshot of parts of it. But you are not supposed to be able to save changes in the snapshot classes to the database.

Jimmy Nilsson's book Chapter 6: Preparing for infrastructure - Querying. Page 226.

Snapshot pattern

Anyone please suggest a good design and architecture book for .Net.

Is there any book I can refer to which has case studies, examples, etc. so that I can update my knowledge well in this field?

In case it's not available for .Net, please suggest in Java also.

Thanks in advance Swapna MC

Here's are a few good enterprise architecture books (based on Java, but the general concepts still apply):

A few of these patterns are a little old, but still useful to know.

If you're interested in WCF for a service-oriented architecture:

Or for framework design:

I would recommend this book: .NET: Architecting Applications for the Enterprise

Not a .net book, but the classic book here is Patterns of Enterprise Application Architecture

I enjoyed Head First Design Patterns:

More design than architecture (obviously) but it makes heavy use of examples. Examples are in Java, btw.

Architectural approaches can vary greatly depending on what you're trying to build. I.e.- Architecting a specific software's internal's, or architecting a distributed system, etc.

For a given software program's internals, I like Patterns of Enterprise Application Architecture as a good reference.

I have also used the SEDA architectural style for some high throughput event-driven applications. The SEDA homepage has the original paper and references to other projects using this style. You might have heard of the Java Open Source projects: MULE and Apache Camel.

Also check out Enterprise Integration Patterns, which is a great companion book to PoEAA. This one pretty much helps you architect the interconnection between distributed systems. Lots of tools in this area... from XMPP to AMQP, to MULE, to JMS, etc.

And I have to suggest reviewing the REST Architectural Style since it is important in today's web software. There is a lot of material about REST, but primarily read (and reread) Roy Fielding's dissertation.

What are the best places to find out everything there is to know about Domain-Driven Design, from beginner to advanced.

  • Books
  • Websites
  • Mailing lists
  • User groups
  • Conferences
  • etc

Applying Domain-Driven Design and Patterns is a very good book on the subject. Lots of good examples as well as discussion of related subjects like test driven development and how they apply.

Also check out

Here are some informative sources:

  • An interview with Eric Evans on Software Engineering Radio
  • A book which applies the principles of DDD using an example in C#
  • A podcast on Getting Started With Domain-Driven Design by Rob Conery
  • A conversation between Scott Hanselman and Rob Conery on Learning DDD.

I recommend Domain Driven Design from Eric Evans, it's a great book on the subject.

I would like to get book(s) that will really give me a complete view of modern ASP.NET development using C#, TDD, ASP.NET MVC, DDD and Design Patterns such as the Repository pattern. I'm very competent with C# and ASP.NET MVC, but want to fill in the gaps.

If you've had a good experience with a book or two that covers these topics could you please share them?

Try Applying Domain Driven Design and Patterns By Jimmy Nillson. It covers DDD and it's patterns in .NET

Guess the scope of topics you have asked is vast to be covered in a single book

Try this One Agile Principles, Patterns, and Practices in C# By Martin and Martin

Book talks mostly about Design Principles, Design Patters, UML Diagrams, Documentation, Refactoring. It doesn't cover ASP.NET and MVC though. YOu need to refer some other books for those.

I'm currently interested in how to architecture good .NET applications and I'm reading or have currently read some of the following books:

Those two Microsoft books really explain how to design .NET applications with high testability using Inversion Of Control and such.

And to be clear, yes they all use design patterns common in TDD, DDD, Dependency Injection, ans so on...

For your needs I would recommend starting with:

Like the title says; it's basically a book on how to to DDD and TDD in a .NET environment.

Here are a few that I would recommend:

I've been reading up on DDD a little bit, and I am confused how this would fit in when using an ORM like NHibernate.

Right now I have a .NET MVC application with fairly "fat" controllers, and I'm trying to figure out how best to fix that. Moving this business logic into the model layer would be the best way to do this, but I am unsure how one would do that.

My application is set up so that NHibernate's session is managed by an HttpModule (gets session / transaction out of my way), which is used by repositories that return the entity objects (Think S#arp arch... turns out a really duplicated a lot of their functionality in this). These repositories are used by DataServices, which right now are just wrappers around the Repositories (one-to-one mapping between them, e.g. UserDataService takes a UserRepository, or actually a Repository). These DataServices right now only ensure that data annotations decorating the entity classes are checked when saving / updating.

In this way, my entities are really just data objects, but do not contain any real logic. While I could put some things in the entity classes (e.g. an "Approve" method), when that action needs to do something like sending an e-mail, or touching other non-related objects, or, for instance, checking to see if there are any users that have the same e-mail before approving, etc., then the entity would need access to other repositories, etc. Injecting these with an IoC wouldn't work with NHibernate, so you'd have to use a factory pattern I'm assuming to get these. I don't see how you would mock those in tests though.

So the next most logical way to do it, I would think, would be to essentially have a service per controller, and extract all of the work being done in the controller currently into methods in each service. I would think that this is breaking with the DDD idea though, as the logic is now no longer contained in the actual model objects.

The other way of looking at that I guess is that each of those services forms a single model with the data object that it works against (Separation of data storage fields and the logic that operates on it), but I just wanted to see what others are doing to solve the "fat controller" issue with DDD while using an ORM like NHibernate that works by returning populated data objects, and the repository model.

Updated I guess my problem is how I'm looking at this: NHibernate seems to put business objects (entities) at the bottom of the stack, which repositories then act on. The repositories are used by services which may use multiple repositories and other services (email, file access) to do things. I.e: App > Services > Repositories > Business Objects

The pure DDD approach I'm reading about seems to reflect an Active Record bias, where the CRUD functions exist in the business objects (This I call User.Delete directly instead of Repository.Delete from a service), and the actual business object handles the logic of things that need to be done in this instance (Like emailing the user, and deleting files belonging to the user, etc.). I.e. App > (Services) > Business Objects > Repositories

With NHibernate, it seems I would be better off using the first approach given the way NHibernate functions, and I am looking for confirmation on my logic. Or if I'm just confused, some clarification on how this layered approach is supposed to work. My understanding is that if I have an "Approve" method that updates the User model, persists it, and lets say, emails a few people, that this method should go on the User entity object, but to allow for proper IoC so I can inject the messagingService, I need to do this in my service layer instead of on the User object.

From a "multiple UI" point of view this makes sense, as the logic to do things is taken out of my UI layer (MVC), and put into these services... but I'm essentially just factoring the logic out to another class instead of doing it directly in the controller, and if I am not ever going to have any other UI's involved, then I've just traded a "fat controller" for a "fat service", since the service is essentially going to encapsulate a method per controller action to do it's work.

The short answer to you question is yes, in fact, I find NHibernate enhances DDD - you can focus on developing (and altering) your domain model with a code first approach, then easily retro-fit persistence later using NHibernate.

As you build out your domain model following DDD, I would expect that much of the business logic that's found you way into you MVC controllers should probably reside in your domain objects. In my first attempt at using ASP.NET MVC I quickly found myself in the same position as yourself - fat controllers and an anemic domain model.

To avoid this, I'm now following the approach of keeping a rich domain model that implements the business logic and using MVC's model as essentially simple data objects used by my views. This simplifies my controllers - they interact with my domain model and provide simple data objects (from the MVC model) to the views.


The pure DDD approach I'm reading about seems to reflect an Active Record bias...

To me the active record pattern means entities are aware of their persistance mechanism and an entity maps directly to a database table record. This is one way of using NHibernate e.g. see Castle Active Record, however, I find this pollutes domain enitities with knowledge of their persistence mechanism. Instead, typically, I'll have a repository per aggregate root in my domain model which implements an abstract repository. The abstract repository provides basic CRUD methods such as:

public IList<TEntity> GetAll()
public TEntity GetById(int id)
public void SaveOrUpdate(TEntity entity)
public void Delete(TEntity entity)

.. which my concrete repositories can supplement/extend.

See this post on The NHibernate FAQ which I've based a lot of my stuff on. Also remember, NHibernate (depending on how you set up your mappings) will allow you to de-persist a complete object graph, i.e. your aggregate root plus all the objects hanging off it and once you've finished working with it, can cascade saves through you entire object graph, this certainly isn't active record.

...since the service is essentially going to encapsulate a method per controller action to do it's work...

I still think you should consider what functionality that you currently have in your controllers should, more logically, be implemented within your domain objects. e.g. in your approval example, I think it would be sensible for an entity to expose an approve method which does whatever it needs to do to within the entity and if, as in your example, needs to send emails, delegate this to a service. Services should be reserved for cross-cutting concerns. Then, once you've finished working with your domain objects, pass them back to your repository to persist changes.

A couple of books I've found useful on these topics are:
Domain-Driven Design by Eric Evans
Applying Domain-Driven Design and Patterns by Jimmy Nilsson

Looking for some reference material where i can get some OO designing problems and solution to practice and improve designing skills.

Thanks for your interest.

EDIT: I have read: - Refactoring by Martin Fowler - Headfirst Design Patterns (It had problem-solution approach but very limited to a pattern in context). and have fare idea about common design patterns.

I am looking for a reference which is very specific to design related problems and solutions.

I liked Applying Domain-Driven Design and Patterns by Jimmy Nilsson. The material is good and the writing is conversational.

i heard that domain driven design pattern but do not know what it is exactly. is it design pattern? if so then how it is different from mvc or mvp. please discuss this. how to implement domain driven design pattern with c#.

For DDD in the C# world, please look at Applying Domain-Driven Design and Patterns: With Examples in C# and .NET . Jimmy Nilsson (the author) is a recognised leader in DDD using a C# slant.

I've just returned from a course where we covered some ways to build enterprise applications (including database applications).

In short I've realised that the way that we have been building our database applications is completely wrong (I won't go into details).

Can anyone recommend a reputable book or website that shows me the "best practice" way for building enterprise, scalable database applications in .Net?

I need this not only to refer to to help me change the way that I'm doing things, but also to show my boss to backup the reasons why I think we need to change the way that we do things.

Do you know any books that explain multi tier architecture (like separation of application server from web server, benefits, drawbacks etc.) ? It would be nice if the book included samples how to fit ASP .NET MVC 3.0 into it, but good comprehensive book on multitier architecture will suffice.


I highly recommend Applying Domain-Driven Design and Patterns: With Examples in C# and .NET by Jimmy Nilsson. It doesn't cover Asp.Net MVC 3 nor does it focus on splitting your app across multiple servers. What it does focus on though is the architecture and design patterns needed to make that setup clean, maintainable, and sustainable. It covers topics like setting up repositories and services, using dependency injection to decouple those services from your web layer, performing test driven development, and of course the whole concept of domain driven design (model-centric development).

It's a fantastic read and a lot easier to consume (in my opinion) than Eric Evans's book. Eric Evans, for all of his genius, is a bit dry for me. Nilsson is a funny guy and really breathes excitement into what should be a dry topic. You'll put the book down energized and more importantly, a lot more equipt to deal with multi-tier (or any, for that matter) development.

I have given the book away to a number of colleagues and former professors, all of whom have reported back that it was a fantastic read. I highly recommend it to any professional developer regardless of what langauge or framework they are currently on.

I am currently reading Applying Domain-Driven Design with Examples in C# and .NET. I have two questions regarding the initial sketch up of the domain model:

  1. I am not a native English speaker, so what does a "Reference Person" mean exactly in the business domain or in English in general ?
  2. The author commented on the sketch up that the although the "Reference Person" class appears in two different aggregates on the diagram, at run time they are the same instance, how is that possible ? if an aggregate root was garbage collected wouldn't that lead to collecting that instance and thus making the other aggregate unstable ?

Here I post the picture we are talking about:

enter image description here

  1. A customer sometime is an organization, not an individual, it may have a list of ReferencePersons that you can contact. We can say that a reference person is the one who represent for an organization. (Aggregate 1)

    When a customer want to place an order, we also need to know exactly the person we are talking to. (Aggregate 2)

  2. You should read carefully, the author commented in the book that "The class ReferencePerson is in two different Aggregates in Figure 4-13, but the instances aren't". It means when you load an order and a customer at a same time from database, the Order.ReferencePerson and Customer.ReferencePersons[index] do not point to the same object in memory even they are the same person.

Further more, even they point to the same instance, in .Net objects will be collected when there is no reference to them. If the aggregate 1 was collected but the aggregate 2 still have a reference to the ReferencePerson A, A still is not collected yet.

I have a VS solution, with the following projects.


but where should the main model class reside? This is usually a cache of a set of objects which are the results from the data access layer and the GUI using virtual grids to view data inside the model. The question would be the same using MVC or MVP


i agree that the model objects go into POCO. so lets say i have an Order object. My question is where do i have the class that stores a collection of orders ??

That depends on your business. Most likely you'll have a collection of orders in a few different places...

On your customer object, each customer should have a collection of orders, so you would have one there.

If you have departments, each department should have a collection of orders they created.

If you have warehouses, each warehouse may have a collection of orders they are responsible for fulfilling.

Some objects have no parent, and that's fine. In my system, we have clients. The real-world owner of the clients is us (the business), but there is no "Us" object in the system. If you're looking to get a list of your clients (in our case) we query the repository for it.

IRespoistory<Client> repository = new Repository<Client>();
IList<Client> clients = repository.GetAllClients();

The same could apply to your orders.

I'd recommend checking out this DDD book:

I'm analyzing a fairly enterprise resource planning software and because an ERP covers many areas from accounting to sales and CRM I have chosen to use Domain Driven Design. Now I have two questions :

  1. What are main APPLIED (not in theory) resources to start DDD?
  2. How can I find out for example to which Domain or Module an "Invoice" belongs ? Does it belongs to "Accounting" or "Sales"?

There may be many examples of such situation where I get confuse when separating Entities and Domains...

How can I overcome this problem ?

  1. There is two resources i would recommend that use DDD in practice: the first one is the one and only famous book Applying Domain-Driven Design and Patterns_ With Examples in C# and .NET.pdf, and the other one is dotNET Domain Driven Design with C# - Problem - Design - Solution.pdf but they both assume you have read Eric Evan's book first.
  2. i don't think anyone is qualified to answer the second question very well, and most people will say it depends on context and you particular application. the hard truth is that DDD is about design and it requires sophisticated skills (it is not easy). so i will suggest you develop your code incrementally with backing tests so you could change you design when the right moment comes (that what eric refers to as a Breakthrough).

I'm trying to create a simple three tier project and I'm on track on implementing the Business Logic layer, right now, this is how my BL looks like

//The Entity/BO
public Customer
    public int CustomerID { get; set; }
    public string CustomerName { get; set; }
    public UserAccount UserAccount { get; set; }
    public List<Subscription> Subscriptions { get; set; }

//The BO Manager
public class CustomerManager

     private CustomerDAL _dal = new CustomerDAL();

    private Customer _customer;

    public void Load(int customerID)
        _customer = GetCustomerByID(customerID);

    public Customer GetCustomer()
        return _customer;

    public Customer GetCustomerByID(int customerID)

        return _dal.GetCustomerByID(customerID);

    public Customer GetCustomer()
        return _customer;

    public UserAccount GetUsersAccount()

        return _dal.GetUsersAccount(_customer.customerID);

    public List<Subscription> GetSubscriptions()
         // I load the subscriptions in the contained customer object, is this ok??
        _customer.Subscriptions = _customer.Subscriptions ?? _dal.GetCustomerSubscriptions(_customer.CustomerID);

        return _customer.Subscriptions;

As you may notice, my object manager is really just a container of my real object (Customer) , and this is where I put my business logic, kinda way of decoupling the business entity to the business logic, this is how I typically use it

        int customerID1 = 1;
        int customerID2 = 2;


        //get customer1 object
        var customer = customerManager.GetCustomer();

        //get customer1 subscriptions
        var customerSubscriptions = customerManager.GetSubscriptions();

        //or this way
        //var customerSubscriptions = customer.Subscriptions;


        //get customer2
        var newCustomer = customerManager.GetCustomer();

        //get customer2 subscriptions
        var customerSubscriptions = customerManager.GetSubscriptions();

As you can see it only holds 1 object at a time, And if i need to manage List of Customers, I probably have to create another manager like CustomerListManager

My question is, Is this the right way of implementing the BL of a three tier/layer design? Or any suggestion on how would you implement it. Thanks.

As others have mentioned before you should have a look at the Repository pattern. I would also recommend to check out the Unit Of Work pattern as well as Domain Driven Design for your application's architecture in general.

You might also have a look into object relational-mapping (ORM) frameworks for .NET like Entity Framework or NHibernate if that's an option for you.

To give you a head-start here are some great resources to get you on the right road:


Online References

Hope that helps.

Lets take a hypothetical project such as a student enrollment system for a music school.

  • Within the system there needs to exist a way to enter student data for a new student interested in receiving instruction at this school and we can assume that students may have access to this functionality through a web site.
  • Part of the enrollment process asks the student the type of instrument for which she would like to receive instruction.
  • As a result of entering information about her preferred musical instrument the behavior will be to assign a default instructor who is assigned to that group of instruments.
  • Before completing the enrollment request the student will be also be able to change the assigned instructor to different instructor who also is listed as able to give instructed for her selected instrument.

Given this description, the part I'm having a little trouble with is how manage the list of possible instructors out of the ones who are able to give instruction for particular instrument in terms of choosing a default instructor for a new student first, and secondly how to use this same data when it comes time to validate the selected instructor before an enrollment is submitted. Other technical constraints are that up to this point I've been using a self validating technique very similar to the one presented in Jimmy Nilsson's book Applying Domain-Driven Design and Patterns so it is mainly unclear to me the best way to go about continuing following self validating techniques when access to external data is necessary which I would normally see as outside of the scope of the entity being tested for validity.

The options I'm aware of:

  1. Move validation outside of the entity itself. Perhaps validation is moved into a set of services or a single service per entity which analyses current state of the whole entity and deems it valid or not and provides for domain events or other value objects to be emitted that give more insight about what validation rules have been broken. In this case I'm still a bit uneasy about how the service would get access to the necessary information about instructors
  2. Allow for access to a instructor repository from necessary entities that are attempting to perform this validation.
  3. Create a service that allows access to a list of instructors by instrument category. Alternatively create two separate services, one that returns whether a given instructor is in the list of instructors for a given category, and another which returns the default instructor for a given category.
  4. Load a list of instructor value objects within my aggregate root (likely student, or a student enrollment request) that can be used for validation either by the aggregate root or entities contained within the root.

In either of the first two cases above it seems like the use of a instructor repository would be overkill because I don't need to access an aggregate root that represents an instructor but instead in my case I would see the instructor as a value object that describes the student enrollment request and having a repository spit back value objects seems to be blurring the lines of what a repository is supposed to be doing. For the last two options it seems wrong two allow access to data from a service or a factory in the case of option 4 since aren't repositories supposed to be in charge of data access such as this? And if repositories are the right place for this logic where are the appropriate places to access or store references to repositories? I've been convinced that there are reasons not to access repositories directly within any entity or value object that makes up the model so I'm wondering if this is a case where I may have to bend on that assumption. I should also mention that I'm pretty new to DDD and I'm just now encountering some of my head scratching moments and attempting not to box myself in so any knowledgeable input on this topic would be valuable.

My answer does not cover the detailed implementation / code as it seems that you are using this as an exercise to learn more about DDD.

Remember that in most cases you'll not be able to get the model right the first time and need to evolve the model. As you “play with it” certain rigid parts will become more flexible to change. (Like a gardening glove as per Eric's analogy). As you gain new insights into the domain, you'll find that you need to introduce new concepts into your model. Using “simple examples” has dangers for example they can lack depth. But simple examples are sometimes needed to get the hang of DDD and fortunately we can evolve the example too ;)

One thing I've heard Eric Evans mention was that if the domain does not feel right or you have trouble expressing something in a model you might be missing a concept. Naturally if you have the concepts in your domain you can “get a feeling” or find a natural place where validation will occur.

Having set the context I thus have a proposition as follow:

Enterprise Patterns and MDA has some complex patterns but the idea you can take away is the CapacityManager of the Inventory archetype as guidance. Unfortunately the model on pg 278 is not available online but have a look at the ServiceInventory archetype.

The instructors are selling their services to students. (Instructors get a salary last time I checked :). If I were to map your example to the Inventory archetype for ideas I would use:

  • Inventory - List of instruments/courses
  • ServiceType - Instrument / Course details, start end etc
  • ServiceInventoryEntry - Instrument + places available (uses capacity manager)
  • ServiceInstance - Enrollment - place in class (Scheduled, Booked, Canceled, Completed)
  • CapacityManager (used by ServiceInventoryEntry)
  • ReservationRequest - Enrollment request

I think the key concept added is the CapacityManager: You can call the ServiceInventoryEntry::getCourses() method which will use the CapacaityManager (service or class) to show you / calculate the available teachers or return the default one. Thus, call it multiple times depending on the context: Default or Propose a list of available places/seats/instructors.

With this model you should be able to find natural place (where and when) to validate. The guidance from Streamlined Object Modeling is to put validation where the data is. Not to be taken as a hard rule but there is a natural tendency for objects to have the proper concerns and data grouped together. For example the capacity manager knows about enrollments and instruments. (From MDA - CapacityManger: Manages utilization of capacity by releasing ServiceInstances)

To get your aggregates see what transactions / changes you'll do so that you can ensure they enforce the invariants (rules). In your example I would make ServiceType(Course) a value object, ServiceInventoryEntry and ReservationRequests aggregate roots. (Depends on how complex you want to take your rules). You can also add Students and Teachers as parties as per the MDA book. I tend to use repositories to get hold of my aggregates and then also rely on inversion of control as per Jimmy's book you referenced.

The reason I like the MDA patterns is that it makes me think of use cases and model concepts that I or the business would not have imagined. But, be careful to only model what you need since the MDA patterns can be big and even enticing. The good thing is that they are designed to be modular or "down scalable".

So in short: - Your aggregate roots should ensure your domain is in a valid state (Rules / Invariants) - Put the validation where the data is. Your model will guide your.

When analyzing life cycle of domain objects, aggregate is basic element for objects grouping. I am having trouble implementing aggregetes in C#.

One short example, with couple of classes, would be very helpful. Or any link on this theme.

class Order {
    public int OrderNumber { get; private set; }
    public Address ShippingAddress { get; private set; }
    public Address BillingAddress { get; private set; }
    private readonly IList<OrderLine> OrderLines { get; private set; }
    public void AddItem(Item item, int quantity) {
        OrderLine orderLine = new OrderLine(item, quantity);
    // constructor etc.

class OrderLine {
    public Item Item { get; private set; }
    public int Quantity { get; private set; }        
    public OrderLine(Item item, int quantity) {
        Item = item;
        Quantity = quantity;

At no point should logic involving OrderLines be exposed outside of an instance of Order. That's the point of aggegrate roots.

For a .NET specific reference, see Applying Domain-Driven Design and Patterns: With Examples in C# and .NET. Of course, the standard reference here is Domain Driven Design: Tackling Complexity in the Heart of Software . There's a good article on MSDN too.

as the question says, i wish to learn OOP in c#. I am aware of the basics of OOP such as what does class means, what is object, and all 6-7 features of OOP. What i dont understand that how to make use this in real application? I get stuck when it comes to using all these features during development (coding).

I have code in VB.NET and now would be doing in C#. I have use VS 2005 and now using VS 2008.

Please suggest me some very good resource to learn (& especially i could implement it also) OOP in C#


Personally, I found the classic Design Patterns book quite an eye-opener when it comes to object-oriented design. From that, all else follows :)

It predates C# with about 5 years, so you will have to look at C++ and SmallTalk code instead, but learning OO is really not about the language, but rather the mindset.

Many people find that Head First Design Patterns is a more digestible alternative, but I have only flipped through it myself (it looks pretty good, though).

Applying Domain-Driven Design and Patterns: With Examples in C# and .NET

Applying Domain-Driven Design and Patterns is the first complete, practical guide to leveraging patterns, domain-driven design, and test-driven development in .NET environments. Drawing on seminal work by Martin Fowler and Eric Evans, Jimmy Nilsson shows how to customize real-world architectures for any .NET application. You'll learn how to prepare domain models for application infrastructure; support business rules; provide persistence support; plan for the presentation layer and UI testing; and design for service orientation or aspect orientation.

Although not the book's only focus, I found Agile Principles, Patterns, and Practices in C# really useful for OOD/OOP. It covers SOLID design principles in an accessible and very readable way. Similar content is also available at the author's (Robert C. Martin) web site, Object Mentor.

Agile Principles, Patterns, and Practices in C# cover

I'm studying enterprise patterns to use with .NET, I read a lot of theory but I don't have sample code to study.

I would like to know if there is any open source project available there uses these patterns so I can have a clear idea of how to use it.

Although it is not an open source project you may find some good samples in this book: "Applying Domain-Driven Design and Patterns: With Examples in C# and .NET"

I would like to know a good introducing book for Repository Pattern using Entity Framework. Do you know any? thanks

Read the book about Entity Framework, relevant parts from the book about enterprise application patterns and the book about domain driven design. You must first understand every single part to use it correctly.

Once you understand topics answer few questions:

  • Why do you need repository?
  • What will repository solve for you?
  • Why is EF itself not sufficient for that?
  • Will it help if you wrap EF to repository?
  • etc.

Until you don't know at least expected answers for these questions you don't need to bother with repository pattern. The main rule of pattern usage: A pattern should be used when it is needed not because it exists. The boom of all these repository articles goes against this rule and moreover most of these articles are wrong using either wrong code (like passing Func<> to queries instead of Expression<Func<>>) or bad assumptions (like saying that using repository will make your code unit testable).

Do you have good literature recommendation for Design Patterns, especially for Data Access layers.

I'm searching for patterns like Repository and Unit of Work. I need those for implementing WebServices, MVC web applications and MVVM desktop applications.

If you are searching specifically for Repository and Unit Of Work patterns then i suggest that you don't read full books because they discuss them i a generic way and you will get overwhelmed, instead look for specific implementations for those patterns in the technology area you are working in.
With that being sad, the two authors that stand behind Repostiory and UnitOfWork patterns are Martin Fowler and Eric Evans with their books Patterns of Enterprise Architecture and Domain Driven Design: Tackling Complexity at the Heart of Software respectively, the latter book is followed by a great book called Applying Domain Driven Design and Patterns with Examples in C# and .NET.
Regarding design patterns in general the authoritative reference is The GoF (Gang of Four) book Design Patterns: Elements of Reusable Object Oriented Software System and a very great book that focuses on the most common patterns in an entertaining manner is Head First Design Patterns.

I am reading the book Applying-Domain-Driven-Design-Pattern.

In its model design, it has the Order hold reference to Customer, but if it was me doing the design, i will probably have the Customer hold reference to Order.

So, the question, when designing unidirectional relationship, how to decide the direction?

I think if this were an order processing system where Orders are the operational-level concept and Customers provided the context for how to process orders, then an OrderService needs to have Orders refer to the Customer who made the Order. On the other hand, as others have pointed out, it's possible for a Customer can be queried for its orders. This is possible in a customer service system, where the help desk. In this case, I can see a CustomerService that needs Customers to have many Orders.

I have started learning about domain driven design. Are there any good tutorials for for learning domain driven design in and C#. I found this book. Any books or advice will be greatly appreciated!

This book by Jimmy Nilsson contains some implementation guidelines specific for C#/.NET. I created a sample project which demonstrates DDD pattern language. It can be found here. It is an implementation of Cargo Booking sample from the 'Blue book'.

I've never asked anything this general before, and I'm not sure if it's going to sound like I'm asking for someone to do my work for me. I'm an experienced programmer but I'm somewhat new to the kinds of design patterns that get talked about on sites like this.

Synopsis of parameters:

(1) There are 3 external systems that are effectively data stores

System1 - REST System2 - WSDL System3 - COM Interop

(2) Data entities are meaningful in 2 of the systems, moving both to and from (the 2 respective systems)

(3) The whole thing is driven by a synchronization manager app.

Synopsis of implementation:

(4) Data entities are defined by interfaces living in a separate namespace.

IFoo IBar IBaz

(5) Work is done by Utility classes that live in a namespace dedicated to the system.

namespace MyCompany.Integrations.System1 {
 public static class Utility {
  public static List<IFoo> GetFoos(DateTime since) {...}
  public static void SaveBazes(List<IBaz> bases) {...}

namespace MyCompany.Integrations.System2 {
 public static class Utility {
  public static void SaveFoos(List<IFoo> foos) {...}
  public static List<IBar> GetBars(DateTime since) {...}

namespace MyCompany.Integrations.System3 {
 public static class Utility {
  public static void SaveFoos(List<IFoo> foos) {...}
  public static void SaveBars(DateTime since) {...}

Question: What existing patterns, if any, is this similar to and are there any areas I might explore to help me learn how to improve my architecture? I know the Utility classes aren't OO. I haven't figured out how to layout classes to get it done in a simple way yet.

Addition: I thought more and based on one response, I think I was not specific enough. I am hoping someone who had more experience tells me how to apply some OO patterns and get away from Utility classes

10,000 foot answer:

You might find Domain Driven Design and Clean Code useful as they give you a set of patterns that work well together and a set of principals for evaluating when to apply a pattern. DDD resources: the book, free quick intro, excellent walkthrough. Clean Code resources: summary, SOLID principles.

Specific answer:

You are already using the Repository pattern (your utility classes) which I'd probably use here as well. The static members can make the code difficult to test but otherwise aren't a problem. If the Repositories become too complex, break out the low-level API communication into Gateways.

Since an entity is split across multiple data sources, consider modelling this explicitly. For example: Person, HumanResourcesPerson, AccountingPerson. Use names understood by the external systems and their business owners (e.g. Employee, Resource). See Single Responsibilty Principle and Ubiquitous Language for some reasoning. These may be full Entities or just Data Transfer Objects (DTOs) depending on how complex they are.

The synchronization might be performed by an Application Service that coordinates the Repositories and Entities.

I would like to use one of the ideas that Jimmy Nilsson mentioned in his book Applying DDD with Patterns, and that is if i have an entity like a Product for example, i would like to take a snapshot of that entity for historic information, something like ProductSnapshot but i wonder how i might be able to implement this with an ORM (i am currently using Entity Framework). The main problem i am facing is that if i have another Entity like OrderLine that receives the Product via its constructor then entity framework would need you to make a public property of the type you wish to persist so this will force me to have something like this:

class OrderLine {
public Product Original Product {get; set;}
public ProductSnapshot Snapshot {get; set;}

and that seems awkward and not intuitive and i don't know how to deal with it properly when it comes to data binding (to which property i should bind), and finally i think that Product is an Entity while ProductSnapshot is a Value Object plus the snapshot is only taken when the OrderLine is accepted and after that the Product is not needed.

When doing DDD, forget that the database exists. This means the ORM doesn't exist either. Now, because you don't have to care about persistence and ORM limits, you can model the ProductSnapshot according to the domain needs.

Create a ProductSnapshot class with all the required members.This class would be a result probably of a SnapshotService.GetSnapshot(Product p) . Once you have the ProductSnapshot just send it to a repository SnapshotsRepository.Save(snapshot) . Being a snapshot, this means it will probably be more of a data structure, a 'dumb' object. It also should be invariable, 'frozen' .

The Repository will use EF to actually save the data. You decide what the EF entities and relations are. ProductSnapshot is a considered to be a business object by the persistence(it doesn't matter if in reality it's just a simple Dto) and the EF entities may look very different (for example, I store business objects in serialized form in a key-value table) according to your querying needs.

Once you define the EF entites you need to map the ProductSnapshot to them. It's very probable that ProductSnapshot itself can be used as an EF Entity so you don't need to do any mapping.

The point is, that taking a snapshot seems to be domain behavior. You deal with the EF only after you have the snapshot and you do exactly as you'd do with any other busines object.

I am a .NET developer wanting to build an SaaS based ecommerce system with B2B and CMS features (custom built, ASP.NET MVC preferably or using Dotnetnuke that enables SaaS scenarios). Technologies would be mainly Microsoft's (.NET 3.5, 4.0, Ajax, jQuery, Asp.NET MVC or MVP, SQL Server/MySql, EF 2.0, NHibernate, WCF, WPF, Window mobile 6.5, TDD/DDD).

I have a developer/architect asking me to produce a product backlog with ecommerce business requirements. I need to educate myself in how to do it intelligently and rapidly and I would use methodology outlined in this course: Agile Requirements Modeling - Personas, User Stories and Use Cases (I cannot attend it and I need to educate myself on how to best follow these practices).

Can somebody recommend any resources (books, videos, open source code, user manuals, real-world samples of product log) that will help me understand modern ecommerce business, interaction design patterns (since I want to have some GUI functionality built it and that will become some of product log items) and using Agile Scrum methodology? The best resource that would help me would be some real world ecommerce Product Backlog and Sprint iterations with possibly prototypes and interaction diagrams.

I know I ask a lot, but I am detailing my wish.

Thanks, Rad

I would recommend Agile Estimating and Planning for an overview of how to organise the project. For a dot net focussed book I'd recommend Applying Domain-Driven Design. There are many other excellent books that could be useful, but I'd begin with those.

Additionally keep an eye on InfoQ for a constant barrage of excellent material and talks. For example, here's a recent one on project metrics.

I want to study some approaches on realizing a project, designing an application, and so on. I'm not referring to Design Patterns as much as i'm referring at some design styles. For example MVC. So, in that order, I need some links, book names or other suggestions to study on this topic. If you have some thoughts, please help me. Thanks.

I would start by reading upon Domain Driven Design. Eric Evans Tackling Complexity in the Heart of Software is a must-read on this topic. I can then recommend reading Jimmy Nilssons Applying Domain Driven Design and Patterns. This book has examples in .NET (C#) but you should be able to apply it to your language of choice.

Code Complete by Steve McConnell is also a good read if you want to learn how to write clean, maintainable code.

If you like Head Firsts books, i can also recommend reading Object-Oriented Analysis & Design.

For the record, MVC is a design pattern.