C# – Confused on how to properly employ a Repository Pattern with Service/Business Layer on top

asp.netcdesign-patternsentity-frameworkrepository

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.

Best Answer

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.