How to fully charge a business entity in a service layer - asp.net-mvc

I can't really find a satisfying solution for that problem. I have a n-layers application :
UI
Presentation (Domain Model used as DTO, ViewModels are then presented)
Business Layer (Domain Model)
Repository and DAL (Data Model)
My problem is that I need to work with full objects in my business layer. However I can't figure out what is the best way to load them. The question may look stupid - and perhaps it is - but I'm very puzzled by it. I have the following classes (just to illustrate):
public class Library
{
int ID {get;set;}
string Name {get;set;}
Book[] Novels {get;set;}
Book[] TextBooks {get;set;}
}
public class Book
{
int ID {get;set;}
Library[] SalePoints {get;set;}
string Name {get;set;}
string Type {get;set;}
}
And I have two Service Methods LoadLibrary and LoadBook whose aim is to populate these respective models. My problem is that it looks like I will get into an infinite loop. I'll explain myself right now.
I have pre-loaded domain models coming from the Repositories (The repositories convert the Data Models into domain models using valueinjecter (unflatenning), so basically the simple fields (int, string, etc..), are populated in the resulting domain model but the IEnumerable properties are not. That's why I'm finishing to load them in the Service Layer. (There are also two reaons why I can't fully load them in my repositories : 1/ I'm using a generic repository and 2/ The loading logic relay on business rules)
Let us say that I do the following :
public class LibrairiesProcessor
{
public Library LoadLibrairyObject(int ID)
{
Library l = UnitOfWork.LibraryRepo.GetByID(ID); // Only retrieve "simple" properties, here it will get the Name and the ID properties;
l.Novels = UnitOfWork.BookRepo.Get(b=>b.LibrairyID==l.ID && b.Type="Novel");
l.TextBooks= UnitOfWork.BookRepo.Get(b=>b.LibrairyID==l.ID && b.Type="TextBook");
for(int i=0;i<l.Novels.Count();i++)
{
l.Novels[i] = BooksProcessor.LoadBookObject(l.Novels[i].ID);
}
}
}
and
public class BooksProcessor
{
public Book LoadBookObject(int ID)
{
Book b = UnitOfWork.LibraryRepo.GetByID(ID); // Only retrieve "simple" properties, here it will get the Name and the ID properties;
b.SalesPoint = // Get From repo using the Unit of work
for(int i=0;i<b.SalesPoint.Count();i++)
{
b.SalesPoint[i] = LibrairyProcessor.LoadLibraryObject(b.SalesPoint[i].ID);
}
}
}
Isn't there an infinite Loop ? LoadLibraryObject() calling LoadBookObject() and vice versa... And especially when you come to the book whose SalePoint is the librairy who triggered LoadBookObject()... at best the same work is done twice, but I really suspect that it will never end.
So I'm wondering if I'm doing the things right. My goal is to have fully loaded objects to avoid wondering if the object is enough loaded before using it, but I'm not sure of the solution I've came up with. How do you usually achieve that ?
It looks like a trivial issue but seriously I can't figure out how to load my stuff. I feel like I have a dilemma :
1/ Manually Populating all the properties and sub properties by using UnitOfWork.Repository, but I will have a lot of code and a lot of redundant code.
2/ Live with partially loaded domain models with some properties set to null, but I really don't want that. And since I'm not working with EF objects directly since my domain model is complex, I can't use their lazy loading stuff.
3/Call the Service LoadObject Methods from one LoadObjectMethod to an other, to avoid code redundancy, but it looks like I'm introducing a lot of recursivity.
How should I handle that ?
Thanks !

This is probably best suited for CodeReview, but here are a few thoughts that may save you some trouble :
Having a whole separate DAL object model might be overkill. Most modern ORMs will take care of the domain objects/DB mapping for you without polluting your domain model with persistence stuff. See Should I create in BLL project class the same like poco class in DAL project and return it to UI project if I want to display data from database?
Having a generic repository seems like a poor excuse for not being able to load lists of sub-entities. As for "the loading logic relies on business rules", if you're referring to the Novels/TextBooks distinction, there are other, less class-intensive ways of doing this.
"since I'm not working with EF objects directly since my domain model is complex, I can't use their lazy loading stuff" : how exactly is your model complex ? Technically speaking, why couldn't you use lazy loading ?
As a good practice, Aggregates shouldn't refer to one another with navigatable properties but with (lists of) ids. The object that got an Aggregate root from a Repository will call another Repository if it wants to load associated aggregate roots.
UnitOfWork.LibraryRepo looks awkward. The UoW should be injected or directly instantiated in the method, not made available as a singleton. Same is true for the Repository. Things will be more testable and loosely coupled if you pass an ILibraryRepo around to the method instead. Unit of Work and Repository are two separate concepts, they somehow converge in Entity Framework but from the outside, they shouldn't look as tightly tied togteher as that.

Related

Best practices with DTOs in ASP.NET MVC Entity Framework

What's the most preferred way to work with Entity Framework and DTOs?
Let's say that after mapping I have objects like:
Author
int id
sting name
List<Book> books
Book
int id
string name
Author author
int authorID
My DTOs
AuthorDTO
int id
sting name
BookDTO
int id
string name
int authorID
Since author can have a lot of books I don't want to retrieve all of them, when for example I'm only interested in authors.
But sometimes I might want to get few authors and filtered books or all books.
I could go with multiple queries AuthorDTO GetAuthor(int id) List<BookDTO> GetBooks(int authorID). But that means several accesses to database.
The ways I see it:
If I had in AuthorDTO field List<BookDTO> books the job could be done. But sometimes I would keep this list empty, if for example I listed only authors. And that means some unconsistency, mess and a lot of details to remember.
Return Tuple<AuthorDTO, List<BookDTO>> it might be a bit confusing.
Define new DTO.
AuthorAndBooksDTO
AuthorDTO author
List<BookDTO> books
The problem with sticking to a sinlge AuthorDTO and selectively filling the List is that you are now forced to keep track of where that DTO came from. Is the list of Books not hydrated, or does this Author simply have no books? Do I have to go back to my controller and call a different method to get a different state of the same DTO? This lacks clarity from the consumer's standpoint.
In my experience, I've leaned the way of more DTOs instead of trying to re-use a set of basic DTOs to represent multiple different sets of data. It requires a bit more "boilerplate", having to set up a whole bunch of similar DTOs and mappings between DTO and Entity, but in the end the specificity and clarity makes the codebase easier to read and manage.
I think some clarification of the issues involved will actually solve your confusion here.
First and most importantly, your entity classes are DTOs. In fact, that's all they are. They're classes that represent a table structure in your database so that data from queries Entity Framework makes can be mapped on to them. In other words, they are literally objects that transfer data. The failing of Microsoft and subsequently far too many MVC developers is to conflate them with big-M Models described by the MVC pattern.
As a result, it makes absolutely zero sense to use Entity Framework to return one or more instances of an entity and then map that to yet another DTO class before finally utilizing it in your code. All you're doing is creating a pointless level of abstraction that adds nothing to your application but yet another thing to maintain.
As far as relationships go, that's where Entity Framework's lazy/eager loading comes in. In order to take advantage of it, though, the property representing the relationship must follow a very specific convention:
public virtual ICollection<Book> Books { get; set; }
If you type it as something like List<Book>, Entity Framework will not touch the relationship at all. It will not ever load the related entities and it will not persist changes made to that property when saving the entity back to the database. The virtual keyword allows Entity Framework to dynamically subclass your entity and override the collection property to add the logic for lazy-loading. Without that, the related entities will only ever be loaded if you explicitly use Load from the EF API.
Assuming your property is defined in that way, then you gain a whole world of abilities. If you want all books belonging to the author you can just interact with author.Books directly (iterate, query, whatever). No queries are made until you do something that requires evaluation of the queryset. EF issues just-in-time queries depending on the information you're requesting from the database. If you do want to load all the related books at the same time you retrieve the author, you can just use Include with your query:
var author = db.Authors.Include(m => m.Books).SingleOrDefault(m => m.Id == id);
My first question would be to ask why you are creating DTO's in the first place? Is there a consumer on the other end that is using this data? Is it a screen? Are you building DTO's just to build DTO's?
Since you tagged the question as MVC i'm going to assume you are sending data to a view. You probably want a ViewModel. This ViewModel should contain all the data that is shown on the View that uses it. Then use entity framework to populate the view model. This may be done with a single query using projections or something complex.
So after all that blathering. I would say you want option 3.
Just like the others said, for clarity reasons, you should avoid creating "generic" DTO's for specific cases.
When you want to sometimes have authors and some of their books then model a DTO for that.
When you need only the authors then create another DTO that is more suited for that.
Or maybe you don't need DTOs, maybe a List containing their names is enough. Or maybe you could in fact use an anonymous type, like new { AuthorId = author.Id, AuthorName = author.Name }. It depends on the situation.
If you're using ASP.NET MVC the DTO you'll want is in fact a ViewModel that best represents your page.
Based on what you've described, you're view model could be something like this
public class BookViewModel{
public int Id {get;set;}
public string Name {get;set;}
}
public class AuthorViewModel{
public int Id {get;set;}
public string Name {get;set;}
public List<BookViewModel> Books {get;set;} = new List<BookViewModel>();
}
public class AuthorsViewModel
{
public List<AuthorViewModel> Authors {get;set;} = new List<AuthorViewModel>();
//add in this class other properties, like the filters used on the page...
public void Load(){
//here you can retrieve the data from your database.
//you could do like this:
//step 1: retrieve data from DB via EF
//step 2: fill in the Authors view models from the data at step 1
}
}
//and in your controller you're calling the Load method to fill you're viewmodel with data from db.
public class AuthorsController{
public ActionResult Index(){
AuthorsViewModel model = new AuthorsViewModel();
model.Load();
return View(model);
}
}

Repository pattern and lazy loading + AutoMapper

I've split my project into (as of this time) 4 layers:
Application (ASP.NET MVC project)
Domain/Model (contains only models with no logic in them at all)
BusinessLogic (right now only "wraps" the repositories)
DAL (Entity Framework, but should be interchangeable)
The MVC Controllers use the business logic "services" to talk to the database through whatever lies beneath the business logic layer, and the controller should not need to tell anyone that "I want this Student, and I also want all his Courses" - this implies that lazy loading should be used.
The thing is, if I just "call through" and return the result to whoever calls the controller action, I can't really control what gets loaded unless I explicitly access the properties on the model to trigger the loading of the graph.
I'd like to use AutoMapper to map from my model to a Dto (one for each model, which defines what gets returned).
Say I have a model like this:
public class Student
{
public string Name {get;set;}
public int Age {get;set;}
public ICollection<Course> Courses {get;set;}
}
And a dto like this:
public class StudentDto
{
public string Name {get;set;}
public ICollection<Course> Courses {get;set;}
}
When AutoMapper does the mapping, it doesen't appear to map the Courses, which is my problem.
Should I be eager-loading at the repository layer instead?
As you have in the Student and StudentDto Automapper should map object graph correctly to the dto. This will work only if lazy loading enabled otherwise you may need to use eager loading.
I think the best way to choose what method to use is to test the performance of both method which will depend on several factors like your data model in the db and the delay between the sql server and your application etc.. .
Edit.. How to choose the best method
How to choose the best method
You need to consider three things,
How many connections that you are going to make with the database. If you are using lazy loading there will be a database call for all the reference points of a navigation properties if referred navigation property is not in the context.
How much data that you are going to retrieve from databaseIf you choose to load all the data in initial query with differed loading it will be too slow when you have huge amount of data to retrieve.
Complexity of the query . When you are using lazy loading the queries will be simple because all the data is not loaded in the initial query. If you use immediate loading it will make quires will be more complex with query paths
read more here

Where should the business logic be in this pattern?

This is my first attempt, after reading a lot about DDD, TDD and Repository / UnitOfWork paterns, to make my own application.
I'm using Entity Framework, MVC 4 on .NET 4.0 (the server that will be running this application is a Windows 2003)
This is the basic simplified pattern logic (The original one uses a IRepository, IUnitOfWork, GenericRepository and extends the EF POCOs with a IEntity interface to give access to the common ID field. But this simplified example will be enough to ask my question)
View -> ViewModel -> Controller <- UnitOfWork <- Repository <- EntityFramework <- Database
View
Model.Employee.GetSeniority()
EmployeeDetailsViewModel
Employee e { get; set; }
Employee
DateTime dateHired { get; set; }
TimeSpan GetSeniority()
{
return DateTime.Today - dateHired;
}
Controller EmployeeDetails()
using(var unitOfWork = new UnitOfWork) {
return View(EmployeeDetailsViewModel model = new EmployeeDetailsViewModel {
e = unitOfWork.GetEmployeRepository().Find(o=>o.id == id)
});
}
UnitOfWork GetEmployeRepository()
return (_employeeRepository ?? _employeeRepository = new EmployeeRepository(this.dbContext));
Repository Find()
dbContext.Configuration.EnableProxyCreation = false;
Employee e = dbContext.Employees.Where(expression);
dbContext.Configuration.EnableProxyCreation = true;
return e;
Everything actually works properly. The problem is that I feel like something is terribly wrong here, and I'm not sure at which layer it should be fixed.
After getting suggested, by a lot of people (Hi Darin), to always pass ViewModels to views and no models, I started doing this. However, what I'm doing (I think) isn't much better. I'm simply encapsulating my model in a viewmodel. At first, it didn't sound that bad since my Find() method would turn proxy off before getting an object, which would result in a persistance-ignorant POCO. However, now that I want to add some logic in the POCOs, I feel like there is something wrong.
I think the problem resides in where my Business logic is and the fact that my Employee POCO should be mapped to a DTO object. However, where should I transfer the Employee POCO to a EmployeeDTO? Should that be the task of the Repository, the Controller or something else? I'm also unsure of where I should put my business logic (as simple as GetSeniority() displayed in the example). Should that be added to the EF POCO through partial classes or should that be in the DTOs? Or is there another missing step in the Employee -> EmployeeDTO transfer?
This is a great question. It looks like you are trying to find clean separation which is fantastic. I would break the problem up. You have Data Access and you have UI display and in between you have your business logic. If you want to use a Domain model approach here is how I would structure it.
Never expose EntityFramework Entity classes outside of Repository. You can choose to return Dto's (POCO') or Domain objects from your repository. If you want Dto's for more separation, that is fine you will just need another layer such as a service layer to convert the Dto's into Domain Objects.
Put your business logic in your Domain Objects. So Domain.Employee.GetSenority() would be on your domain object.
Any logic that does not fit in your Domain Objects can reside in your UnitOfWork or Service Layer.
Convert Domain objects to ViewModel in controller. At this point map Employee.GetSenority() to MyViewModel.Senority property. Basically your ViewModel is a Dto and only contains view specific logic which typically is not much.
Where do you call the repository. You could use the UnitOfWork pattern as you have it or simply create a Service Layer class. The key here is that these should be useable to other application types. For instance if you were to write a desktop or Windows 8 Style App, you would likely want to reuse either of these along with your Domain Entities.
I'm sure you are having fun with this. Good luck.

Onion Architecture - Repository Vs Service?

I am learning the well-known Onion Architecture from Jeffrey Palermo.
Not specific to this pattern, but I cannot see clearly the separation between repositories and domain services.
I (mis)understand that repository concerns data access and service are more about business layer (reference one or more repositories).
In many examples, a repository seems to have some kind of business logic behind like GetAllProductsByCategoryId or GetAllXXXBySomeCriteriaYYY.
For lists, it seems that service is just a wrapper on repository without any logic.
For hierarchies (parent/children/children), it is almost the same problem : is it the role of repository to load the complete hierarchy ?
The repository is not a gateway to access Database. It is an abstraction that allow you to store and load domain objects from some form of persistence store. (Database, Cache or even plain Collection). It take or return the domain objects instead of its internal field, hence it is an object oriented interface.
It is not recommended to add some methods like GetAllProductsByCategoryId or GetProductByName to the repository, because you will add more and more methods the repository as your use case/ object field count increase. Instead it is better to have a query method on the repository which takes a Specification. You can pass different implementations of the Specification to retrieve the products.
Overall, the goal of repository pattern is to create a storage abstraction that does not require changes when the use cases changes. This article talks about the Repository pattern in domain modelling in great detail. You may be interested.
For the second question: If I see a ProductRepository in the code, I'd expect that it returns me a list of Product. I also expect that each of the Product instance is complete. For example, if Product has a reference to ProductDetail object, I'd expect that Product.getDetail() returns me a ProductDetail instance rather than null. Maybe the implementation of the repository load ProductDetail together with Product, maybe the getDetail() method invoke ProductDetailRepository on the fly. I don't really care as a user of the repository. It is also possible that the Product only returns a ProductDetail id when I call getDetail(). It is perfect fine from the repository's contract point of view. However it complicates my client code and forces me to call ProductDetailRepository myself.
By the way, I've seen many service classes that solely wrap the repository classes in my past. I think it is an anti-pattern. It is better to have the callers of the services to use the repositories directly.
Repository pattern mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects.
So, repositories is to provide interface for CRUD operation on domain entities. Remember that Repositories deals with whole Aggregate.
Aggregates are groups of things that belong together. An Aggregate Root is the thing that holds them all together.
Example Order and OrderLines:
OrderLines have no reason to exist without their parent Order, nor can they belong to any other Order. In this case, Order and OrderLines would probably be an Aggregate, and the Order would be the Aggregate Root
Business logic should be in Domain Entities, not in Repository layer , application logic should be in service layer like your mention, services in here play a role as coordinator between repositoies.
While I'm still struggling with this, I want to post as an answer but also I accept (and want) feedback about this.
In the example GetProductsByCategory(int id)
First, let's think from the initial need. We hit a controller, probably the CategoryController so you have something like:
public CategoryController(ICategoryService service) {
// here we inject our service and keep a private variable.
}
public IHttpActionResult Category(int id) {
CategoryViewModel model = something.GetCategoryViewModel(id);
return View()
}
so far, so good. We need to declare 'something' that creates the view model.
Let's simplify and say:
public IHttpActionResult Category(int id) {
var dependencies = service.GetDependenciesForCategory(id);
CategoryViewModel model = new CategoryViewModel(dependencies);
return View()
}
ok, what are dependencies ? We maybe need the category tree, the products, the page, how many total products, etc.
so if we implemented this in a repository way, this could look like more or less like this :
public IHttpActionResult Category(int id) {
var products = repository.GetCategoryProducts(id);
var category = repository.GetCategory(id); // full details of the category
var childs = repository.GetCategoriesSummary(category.childs);
CategoryViewModel model = new CategoryViewModel(products, category, childs); // awouch!
return View()
}
instead, back to services :
public IHttpActionResult Category(int id) {
var category = service.GetCategory(id);
if (category == null) return NotFound(); //
var model = new CategoryViewModel(category);
return View(model);
}
much better, but what is exactly inside service.GetCategory(id) ?
public CategoryService(ICategoryRespository categoryRepository, IProductRepository productRepository) {
// same dependency injection here
public Category GetCategory(int id) {
var category = categoryRepository.Get(id);
var childs = categoryRepository.Get(category.childs) // int[] of ids
var products = productRepository.GetByCategory(id) // this doesn't look that good...
return category;
}
}
Let's try another approach, the unit of work, I will use Entity framework as the UoW and Repositories, so no need to create those.
public CategoryService(DbContext db) {
// same dependency injection here
public Category GetCategory(int id) {
var category = db.Category.Include(c=> c.Childs).Include(c=> c.Products).Find(id);
return category;
}
}
So here we are using the 'query' syntax instead of the method syntax, but instead of implementing our own complex, we can use our ORM. Also, we have access to ALL repositories, so we can still do our Unit of work inside our service.
Now we need to select which data we want, I probably don't want all the fields of my entities.
The best place I can see this is happening is actually on the ViewModel, each ViewModel may need to map it's own data, so let's change the implementation of the service again.
public CategoryService(DbContext db) {
// same dependency injection here
public Category GetCategory(int id) {
var category = db.Category.Find(id);
return category;
}
}
so where are all the products and inner categories?
let's take a look at the ViewModel, remember this will ONLY map data to values, if you are doing something else here, you are probably giving too much responsibility to your ViewModel.
public CategoryViewModel(Category category) {
Name = category.Name;
Id = category.Id;
Products = category.Products.Select(p=> new CategoryProductViewModel(p));
Childs = category.Childs.Select(c => c.Name); // only childs names.
}
you can imagine the CategoryProductViewModel by yourself right now.
BUT (why is there always a but??)
We are doing 3 db hits, and we are fetching all the category fields because of the Find. Also Lazy Loading must be enable. Not a real solution isn't it ?
To improve this, we can change find with where... but this will delegate the Single or Find to the ViewModel, also it will return an IQueryable<Category>, where we know it should be exactly one.
Remember I said "I'm still struggling?" this is mostly why. To fix this, we should return the exact needed data from the service (also know as the ..... you know it .... yes! the ViewModel).
so let's back to our controller :
public IHttpActionResult Category(int id) {
var model = service.GetProductCategoryViewModel(id);
if (category == null) return NotFound(); //
return View(model);
}
inside the GetProductCategoryViewModel method, we can call private methods that return the different pieces and assemble them as the ViewModel.
this is bad, now my services know about viewmodels... let's fix that.
We create an interface, this interface is the actual contract of what this method will return.
ICategoryWithProductsAndChildsIds // quite verbose, i know.
nice, now we only need to declare our ViewModel as
public class CategoryViewModel : ICategoryWithProductsAndChildsIds
and implement it the way we want.
The interface looks like it has too many things, of course it can be splitted with ICategoryBasic, IProducts, IChilds, or whatever you may want to name those.
So when we implement another viewModel, we can choose to do only IProducts.
We can have our services having methods (private or not) to retrieve those contracts, and glue the pieces in the service layer. (Easy to say than done)
When I get into a fully working code, I might create a blog post or a github repo, but for now, I don't have it yet, so this is all for now.
I believe the Repository should be only for CRUD operations.
public interface IRepository<T>
{
Add(T)
Remove(T)
Get(id)
...
}
So IRepository would have: Add, Remove, Update, Get, GetAll and possibly a version of each of those that takes a list, i.e, AddMany, RemoveMany, etc.
For performing search retrieval operations you should have a second interface such as an IFinder. You can either go with a specification, so IFinder could have a Find(criteria) method that takes criterias. Or you can go with things like IPersonFinder which would define custom functions such as: a FindPersonByName, FindPersonByAge etc.
public interface IMyObjectFinder
{
FindByName(name)
FindByEmail(email)
FindAllSmallerThen(amount)
FindAllThatArePartOf(group)
...
}
The alternative would be:
public interface IFinder<T>
{
Find(criterias)
}
This second approach is more complex. You need to define a strategy for the criterias. Are you going to use a query language of some sort, or a more simple key-value association, etc. The full power of the interface is also harder to understand from simply looking at it. It's also easier to leak implementations with this method, because the criterias could be based around a particular type of persistence system, like if you take a SQL query as criteria for example. On the other hand, it might prevent you from having to continuously come back to the IFinder because you've hit a special use case that requires a more specific query. I say it might, because your criteria strategy will not necessarily cover 100% of the querying use cases you might need.
You could also decide to mix both together, and have an IFinder defining a Find method, and IMyObjectFinders that implement IFinder, but also add custom methods such as FindByName.
The service acts as a supervisor. Say you need to retrieve an item but must also process the item before it is returned to the client, and that processing might require information found in other items. So the service would retrieve all appropriate items using the Repositories and the Finders, it would then send the item to be processed to objects that encapsulates the necessary processing logic, and finally it would return the item requested by the client. Sometime, no processing and no extra retrievals will be required, in such cases, you don't need to have a service. You can have clients directly call into the Repositories and the Finders. This is one difference with the Onion and a Layered architecture, in the Onion, everything that is more outside can access everything more inside, not only the layer before it.
It would be the role of the repository to load the full hierarchy of what is needed to properly construct the item that it returns. So if your repository returns an item that has a List of another type of item, it should already resolve that. Personally though, I like to design my objects so that they don't contain references to other items, because it makes the repository more complex. I prefer to have my objects keep the Id of other items, so that if the client really needs that other item, he can query it again with the proper Repository given the Id. This flattens out all items returned by the Repositories, yet still let's you create hierarchies if you need to.
You could, if you really felt the need to, add a restraining mechanism to your Repository, so that you can specify exactly which field of the item you need. Say you have a Person, and only care for his name, you could do Get(id, name) and the Repository would not bother with getting every field of the Person, only it's name field. Doing this though, adds considerable complexity to the repository. And doing this with hierarchical objects is even more complex, especially if you want to restrict fields inside fields of fields. So I don't really recommend it. The only good reason for this, to me, would be cases where performance is critical, and nothing else can be done to improve the performance.
In Domain Driven Design the repository is responsible for retrieving the whole Aggregate.
Onion and Hexagonal Architectures purpose is to invert the dependency from domain->data access.
Rather than having a UI->api->domain->data-access,
you'll have something like UI->api->domain**<-**data-access
To make your most important asset, the domain logic, is in the center and free of external dependencies.
Generally by splitting the Repository into Interface/Implementation and putting the interface along with the business logic.
Now to services, there's more that one type of services:
Application Services: your controller and view model, which are external concerns for UI and display and are not part of the domain
Domain Services: which provide domain logic. In you're case if the logic you're having in application services starts to do more that it's presentation duties. you should look at extracting to a domain service
Infrastructure Services: which would, as with repositories, have an interface within the domain, and an implementation in the outer layers
#Bart Calixto, you may have a look at CQRS, building your view model is too complex when you're trying to use Repositories which you design for domain logic.
you could just rewrite another repo for the ViewModel, using SQL joins for example, and it doesn't have to be in the domain
is it the role of repository to load the complete hierarchy ?
Short answer: yes, if the repository's outcome is a hierarchy
The role of repository is to load whatever you want, in any shape you need, from the datasource (e.g. database, file system, Lucene index, etc).
Let's suppose a repository (interface) has the GetSomeHierarchyOrListBySomeCriteria operation - the operation, its parameters and its outcome are part of the application core!
Let's focus on the outcome: it doesn't matter it's shape (list, hierarchy, etc), the repository implementation is supposed to do everything necessary to return it.
If one is using a NoSql database than GetSomeHierarchyOrListBySomeCriteria implementation might need only one NoSql-database-query with no other conversions or transformations to get the desired outcome (e.g. hierarchy). For a SQL database on the other hand, the same outcome might imply multiple queries and complex conversions or transformations - but that's an implementation detail, the repository interface is the same.
repositories vs domain services
According to The Onion Architecture : part 1, and I'm pointing here about the official page, not someone's else interpretation:
The first layer around the Domain Model is typically where we would
find interfaces that provide object saving and retrieving behavior,
called repository interfaces. [...] Only the interface is in the application core.
Notice the Domain Services layer above Domain Model one.
Starting with the second official page, The Onion Architecture : part 2, the author forgets about Domain Services layer and is depicting IConferenceRepository as part of the Object Services layer which is right above Domain Model, replacing Domain Services layer! The Object Services layer continues in The Onion Architecture : part 3, so I ask: what Domain Services? :)))
It seems to me that author's intent for Object Services or Domain Services is to consist only of repositories, otherwise he leaves no clue for something else.

Real World ASP.NET MVC Repositories

In the real world, Controllers can potentially need to use data from a variety of database tables and other data stores. For example:
[Authorize]
public class MembersController : Controller
{
ICourseRepository repCourse;
IUserCourseRepository repUserCourse;
IMember member;
public MembersController(ICourseRepository repCourse, IUserCourseRepository repUserCourse, IMember member)
{
this.repCourse = repCourse;
this.repUserCourse = repUserCourse;
this.member = member;
}
So:
Should I use a repository for each table?
I guess this is where the concept of agregates comes into play? Should I have one Repository per aggregate?
Do I just add as many Repositories as I need to the constructor of the Controller?
Is this a sign that my design is wrong?
NOTE:
The IMember interface essentially represents a helper object that puts a nice face on the Membership provider. Ie, it puts all the code in one place. For example:
Guid userId;
public Guid UserId
{
get
{
if (userId == null)
{
try
{
userId = (Guid) Membership.GetUser().ProviderUserKey;
}
catch { }
}
return userId;
}
}
One problem with that is surely caching this kind of output. I can feel another question coming on.
EDIT:
I'm using Ninject for DI and am pretty sold on the whole DI, DDD and TDD thing. Well, sort of. I also try to be a pragmatist...
1. Should I use a repository for each table?
Probably not. If you have a repository per table, you are essentially doing Active Record. I also personally prefer to avoid calling these classes "Repository" because of the confusion that can occur between Domain Driven Design's concept of a "Repository" and the class-per-table "Repository" that seems to have become commonly used with Linq2SQL, SubSonic, etc. and many MVC tutorials.
2. I guess this is where the concept of agregates comes into play? Should I have one Repository per aggregate?
Yes and yes. If you are going to go this route.
'3.' Do I just add as many Repositories as I need to the constructor of the Controller?
I don't let my controllers touch my repositories directly. And I don't let my Views touch my domain classes directly, either.
Instead, my controllers have Query classes that are responsible for returning View Models. The Query classes reference whatever repositories (or other sources of data) they need to compile the View Model.
Well #awrigley, here is my advise:
Q: Should I use a repository for each table?
A: No, as you mentioned on question 2. use a repository per aggregate and perform the operations on aggregate root only.
Q: Do I just add as many Repositories as I need to the constructor of the Controller?
A: I guess you´re using IoC and constructor-injection, well, in this case, make sure you only pass real dependencies. this post may help you decide on this topic.
(pst! that empty catch is not a nice thing!!) ;)
Cheers!
This all depends on how "Domain Driven Design" your going to be. Do you know what an Aggregate Root is? Most of the time a generically typed repository that can do all your basic CRUD will suffice. Its only when you start having thick models with context and boundaries that this starts to matter.

Resources