I'm building a ASP.NET Web Api 2 solution for learning purposes, and I've hit a snag. I was wondering if anyone could tell me what exactly it is that I'm missing.

My Web Api solution has 4 Layers:

  • Data, which contains the Data Models ( POCOs ), Fluent API Mappings, EF Context, Migrations and Seeding
  • Repository, which implements CRUD for all Data Models and returns the business Models
  • Domain / Service / Business which supplies the IRepository interface, and should hold services which implement the application's business logic. Also contains the Business Models.
  • Web, the Web Api controllers and DI / IoC to tie everything together.

References are as follows: Data < Repository > Domain

Web references all 3 layers for DI.

The idea behind the separate domain layer is that it is completely oblivious to anything that happens in the Data or Repository layer. It simply outlines its requirements by providing the IRepository for the Repository layer, and the Business Models that it wants to get as a result. It's up to the Repository layer to meet the Domain Layer's requests.

Here is my conundrum:

  • Since Domain has no ties to Data, it does not know anything about the structure of the Data model. This means that the repository layer needs to convert everything to the Business Model before returning it. - I suppose I could return it as a generic object, and then map the generic object to the business model inside the Domain Layer. Would that be more appropriate?
  • Again, since Domain does not know anything about the Data Model, I can't pass any expressions to apply on the data set to my Repository. This means that for every property I want to WHERE, I'd have to create a POCO specific Repository with matching IBussinessModelRepository which outlines it's requirements, and then implement that requirement. This quickly gets tedious though, as it calls for a bunch of "GetByProp1", "GetByProp2" - monkey code central.
  • What if I want to create a composite business model that requires a complex query to hydrate? Is my only option to create yet another IBusinessRepository with a matching Repository and then write the complex query in the repository layer? If that is the case, then it feels like the service layer is mostly just another step that passes along non-crud requests to specific repositories.
  • Is it proper for web API controllers to send requests directly to the repository? It would seem pretty silly to route all CRUD requests through the service layer, which just passes the request to the repository layer anyway. No, it's not as the service layer should be the entry point for all operations. ( With Web just acting as a consumer of the services offered. )
  • I currently don't use a Unit of Work because there is a lot of mixed opinions when it comes to UoW + EF. I'm not yet experienced enough to be on either side of the fence. Would a UoW be helpful in this scenario?

I feel like I am missing a vital part in what makes this pattern / layer approach tick.

I know that I could easily proceed by cheating ( i.e. give service access to data specific stuff like the context ), but I'm more interested in learning how to do it the proper way.

The research I have done so far yielded results that vary wildly:

  • From the Repository using AutoMapper to change the type to the business model without actually executing the query, allowing the service layer to pass Business Model Expressions which can then be applied and then running the query, returning the mapped result -- sounds great, except that approach does not seem to work for me due to AutoMapper not being able to deal with my Models having recursive nav properties.
  • To the service layer just interfacing directly with the POCOs. ( And thus having direct access to the DAL )

What am I missing?

Edit to explain more about my code:

My Generic Repository on Github contains CRUD methods like this one:

public abstract class RepositoryBase<TData, TDomain, TId> : IRepository<TDomain, TId> where TDomain : EntityBase<TId>, new() where TData : class, IDataEntity<TId>, new()
    private readonly ShortStuffContext _context;

    public RepositoryBase(ShortStuffContext context)
        _context = context;

    public IEnumerable<TDomain> GetAll()
        return _context.Set<TData>().BuildQuery<TData, TDomain>();

BuildQuery is a LINQ Extension which either grabs all entities, or can take a expression to fetch a single entity and then uses ValueInjecter to map the Data Model to the Domain Model.

The repository methods are requested by the Domain Layer via Interface:

public interface IRepository<TDomain, TId> where TDomain : EntityBase<TId>
    IEnumerable<TDomain> GetAll();

The RepositoryBase is extended by Repositories for the individual POCOs, which currently sit empty, only providing TData, TDomain and TId to the Repository Base:

public class UserRepository : RepositoryBase<Data.Entities.User, User, decimal>
    public UserRepository(ShortStuffContext context)
        : base(context)

Which can be requested by the Domain Layer via Constructor Injection IRepository<User, decimal> UserRepository through a ninject InRequestScope binding.

  • "and should hold services which implement the application's business logic. Also contains the Business Models." Most businesses have behaviour, so why not put the business logic in your model? Otherwise, what are you modelling? Jul 8, 2014 at 5:52
  • @StefanBilliet Hello Stefan, my business models currently are copies the basic POCOs with some minor changes - IEnumerable instead of ICollection for example. Additionally they have self-validation business logic baked in. Later on I would of course create specialized business models for more specific tasks. Currently, their purpose is soley for self-validation and to be returned from CRUD repository calls, to make domain & web independent from the POCOs.
    – Bio2hazard
    Jul 8, 2014 at 6:49
  • What kind of business logic are we talking about here? Jul 8, 2014 at 8:29

1 Answer 1


How large is your application? There's a good chance you're overthinking this. Unless the application is a large, enterprise-grade application, the high degree of loose coupling you are advocating is probably unnecessary.

If you decide that this level of loose coupling is still necessary, create a service layer that returns "service" objects. This fulfills a similar function to View Models in MVC. You will then write code in your service layer that maps objects from your domain model to your service model.

Note that part of your struggle may be due to the fact that, while your Data Repository is returning CRUD objects, your Service Layer should be returning the result of actions. For example:

public InvoiceView GetInvoice(int invoiceID);

returns a InvoiceView object containing whatever data you wish to expose to the public, including Name, Address, Line Items and so forth, from several different tables/objects in your domain.

public class InvoiceView
    public int InvoiceID;
    public Address ShippingAddress;
    public Address BillingAddress;
    public List<LineItem> LineItems;

Similarly, there will be Service Layer methods that simply performs an action and returns an object indicating the result of the action:

public TransactionResult Transfer(
    int sourceAccountID, int targetAccountID, Money amount, ValidationToken token);

IMPORTANT: You'll never be able to completely decouple from your data. Your consumer will always have to have some knowledge of the data, even if it's just an object ID or UUID.

  • Hey, thank you for your response. My project is a Twitter-Clone built with Web API as a learning project ( for a potential enterprise position ), you can view the source code on my Github. While this project certainly does not require the level of decoupling I am applying, I want to learn about how to do it. It's more about the journey than the destination. My domain layer knows that every POCO has a property named ID, that's it. So you propose to give service full context / DAL access and return unified objects, right?
    – Bio2hazard
    Jul 8, 2014 at 2:01
  • That would be my guess, yes. Jul 8, 2014 at 2:47
  • A few things I am unclear about: When you say create a service layer ... you will then write code in your service layer etc. are you refering to changing the way my current service layer works ( in my solution called Data.Domain ), or introducing a additional 5th layer? Also, what is the difference between the "result of action xView" and the business models as I currently have them, since both would be models defined by the service layer, and my business models currently are "objects containing whatever data i wish to expose to the public".
    – Bio2hazard
    Jul 8, 2014 at 3:23
  • If you already have a service layer, use the one you have. The result of an action might contain several domain objects, not just the result of a single CRUD operation. I'll add an example to my answer. Jul 8, 2014 at 3:28
  • thank you for providing more information. So essentially the xView is a purpose-oriented class, composed of values and business models to fulfil the given purpose. That makes sense. But that still leaves me wondering: What exactly is the best way to hydrate that class? If I use my existing crud methods, I'd have to: First GET the User, then GET all messages with the user as creator, then GET all retweets with that creator, and I end up running 3 queries for something I could've done with 1 query directly in the repo. That I feel is the key aspect I am missing.
    – Bio2hazard
    Jul 8, 2014 at 3:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.