S#arp Architecture: How to arrange Application Services - asp.net-mvc

With S#arp Architecture, my understanding is that domain logic (aka business logic) that operates on more than one type of entity is best handled by the Application Services layer.
So the classes in Application Services will need access to the Repositories. Presumably then you inject the Repositories in via the constructors. Because there is one class of repository per entity type, any fairly realistic task is going to need access to several repositories. So you might have an Application Services class looking like this:
public class DogTasks
{
public DogTasks(IRepository<Dog> dogRepository,
IRepository<Trick> trickRepository,
IRepository<DogTrick> dogTrickRepository,
IRepository<Lesson> lessonRepository)
{
// etc
}
public void TeachDogNewTrickAtALesson(int dogID, string trickName, int lessonID)
{
// etc
}
// other methods, etc
}
This Tasks class can then be injected into the relevant Controller.
So far, I think I get it. But I am perturbed by the following:
When I need a new Application Services method that uses a combination of repositories that I don't have yet, I have to choose between changing the constructor for one of my existing classes to accept the new repositories, or starting a new class altogether. Adding arguments to constructors upsets a lot of the unit tests, but proliferating new classes doesn't seem good either.
When Controllers need to do simple Repository operations (like a get) it makes sense to inject the repositories into the Controllers as well as the Application Services classes. But then I get the same 'changing constructor arguments' issue. The other alternative seems to be to only let the Application Services layer play with the Repositories, but then you get a lot of boilerplate code added to the Application Services to do very simple things.
These sorts of things make me think I might be doing it wrong. So how should a good Application Services layer be organised?
e.g. Do you have lots of classes that just do one task each? Or do you clump related tasks together along entity lines? How do you deal with tasks that need a lot of repositories? Does needing a lot of repositories for a task mean its time to go back to the drawing board?

First, I'd like to counter your assumption that each entity needs its own repository. Per, Eric Evans "Domain Driven Design"
Repositories give access to selected aggregate roots. Repositories are prohibited from the interior of an aggregate.
Given your example, a dog has a set of tricks that it has learned. When you want to add a new trick to the dog, you'd do something like this:
var dog = dogRepository.Get(dogId);
dog.Tricks.Add(newTrick);
dogRepository.SaveOrUpdate(dog);
When I need a new Application Services method that uses a combination of repositories that I don't have yet,
I'm not sure what you mean by this. But I think if you stick to using repositories for aggregate roots, you're not going to run into such messy code.
The other alternative seems to be to
only let the Application Services
layer play with the Repositories, but
then you get a lot of boilerplate code
added to the Application Services to
do very simple things.
Controllers orchestrate. Think of controllers as a part of the UI, they move you from page to page. I will admit that for simple things, it seems simpler to just inject a repository into the controller, but when your project grows the separation will help a lot, especially if you end up having another application hook into your Tasks layer. Keep repositories out of controllers.
e.g. Do you have lots of classes that
just do one task each? Or do you clump
related tasks together along entity
lines? How do you deal with tasks that
need a lot of repositories? Does
needing a lot of repositories for a
task mean its time to go back to the
drawing board?
Again, I think this goes back to defining aggregate roots. Having 4-5 repositories in a task isn't that big of a deal. I usually organize my tasks by what the application is trying to do, with the idea that if the UI changes to, say, an external JSON request, you just need to call the right task.
Hope this answers your question. Feel free to post this on the Sharp mailing list, you might get a better response there.
Edit based on comments:
Check out Who Can Help Me (https://github.com/sharparchitecture/Who-Can-Help-Me) for an example of how to use the ApplicationServices/Tasks layer. They have a fairly small domain model so each entity has its own task.
I think you're confusing terminology a bit, or perhaps I'm being unclear. The idea behind an ApplicationServices layer is to further abstract the UI from the domain layer. Repositories are domain layer entities, and knowledge of them should not be in the controller. If you end up swapping out ORM or even moving to a document-based storage system, you'll see why this abstraction makes it really convenient, you just need to make sure your ApplicationServices contracts are working and don't have to muck about in the controllers.
But, don't confuse the need for ApplicationServices as a way of future proofing. It simply allows for further decoupling between your layers and decoupling is nearly always a good thing.
Again, for a project you're working on solo, all this might seem a bit of overkill. When you're working with other developers, all this abstraction is really, really nice. You can have a team working on upstream domain issues, and a team working on the presentation layer, and have a nice separation of concerns.

Have you heard about Abstract Factory pattern? It solves this problem in a nice way:
public interface IDalFactory
{
// One way
IRepository<Trick> TrickRepository { get; }
IRepository<Dog> DogRepository { get; }
...
// Other way
IRepository<T> GetRepository<T>();
}
public DogTasks
{
public DogTasks(IDalFactory dalFactory)
{
...
}
}
It is up to you how do you implement IDalFacotry. I usually using lazy initialization of repositories. Once repository is created it is internally stored and reused. One factory instance is created per http request.
The cons is that you don't have control over factories exposed to your application service. But that are your choices. Adding new repositories to constructor or using factory.

Related

Service layer and project structure in ASP.NET MVC 5 without repository and UoW patterns

I'd like to create a good app in ASP.NET MVC 5 using EF 6 Code first concept. I want it to be well-designed i.e. having generally speaking: Presentation, Logic and Data layers separated. I want it to be testable :)
Here's my idea and some issues related with creating application
Presentation layer: It's my whole MVC - view models(not models), views, controllers
I believe that's validation should be done somewhere else (in my opinion - it's a part of business logic) but it's quite convenient to use attributes from the DataAnnotations namespace in ViewModelds and check validation in controller.
Logic layer: Services - classes with their interfaces to rule business logic.
I put there functions like: AddNewPerson(PersonViewModel Person), SendMessageToPerson(...).
They will use DB context to make their actions (there's a chance that not all of them will be relying on context). There's a direct connection between service and db - I mean the service class have reference do context.
Where should I do mapping between ViewModel and Model? I've heard that service is a bad place for it - so maybe in controllers. I've heard that service should do the work related with db exclusively.
Is it right? Is my picture of service layer is good?
Data layer: I've read about Repository and UoW patterns a lot. There're some articles which suggest that EF6 implements these two things. I don't want to create extra code if there's no need for such a behavior. The question is: am i right to assume that i don't need them?
Here's my flow:
View<->Controllers(using ViewModels)<->Services(using Models)<->DB.
**I'm gonna use DI in my project.
What do you think about my project structure?
There is no reason to use a Unit of Work pattern with Entity Framework if you have no need to create a generic data access mechanism. You would only do this if you were:
using a data access technology that did not natively support a Unit of work pattern (EF does)
Wanted to be able to swap out data providers sometime in the future.. however, this is not as easy as it might seem as it's very hard NOT to introduce dependencies on specific data technologies even when using an Unit of Work (maybe even BECAUSE you are)... or
You need to have a way of unifying disparate data sources into an atomic transaction.
If none of those are the case, you most likely don't need a custom Unit of Work. A Repository, on the other hand can be useful... but with EF6 many of the benefits of a Repository are also available since EF6 provides mocking interfaces for testing. Regardless, stay away from a generic repository unless it's simply an implementation detail of your concrete repositories. Exposing generic repositories to your other layers is a huge abstraction leak...
I always use a Repository/Service/Façade pattern though to create a separation between my data and business (and UI and business for that matter) layers. It provides a convenient way to mock without having to mock your data access itself and it decouples your logic from the specific that are introduced by the Linq layer used by EF (Linq is relatively generic, but there are things that are specific to EF), a façade/repository/server interface decouples that).
In general, you're on the right path... However, let me point out that using Data Attributes on your view models is a good thing. This centralizes your validation on your model, rather than making you put validation logic all over the place.
You're correct that you need validation in your business logic as well, but your mistake is the assumption that you should only have it on the business logic. You need validation at all layers of your application.. And in particular, your UI validation may have different requirements than your business logic validation.
For instance, you may implement creating a new account as a multi-step wizard in your UI, this would require different validation than your business layer because each step has only a subset of the validation of the total object. Or you might require that your mobile interface has different validation requirements from your web site (one might use a captcha, while the other might use a touch based human validation for instance).
Either way, it's important to keep in mind that validation is important both at the client, server, and various layers...
Ok, let’s clarify a few things...
The notion of ViewModel (or the actual wording of ViewModel) is something introduced by Microsoft Martin Fowler. In fact, a ViewModel is nothing more than a simple class.
In reality, your Views are strongly typed to classes. Period. To avoid confusion, the wording ViewModel came up to help people understand that
“this class, will be used by your View”
hence why we call them ViewModel.
In addition, although many books, articles and examples use the word ViewModel, let's not forget that it's nothing more than just a Model.
In fact, did you ever noticed why there is a Models folder inside an MVC application and not a ViewModels folder?
Also, ever noticed how at the top of a View you have #model directive and not # viewmodel directive?
That's because everything could be a model.
By the way, for clarity, you are more than welcomed to delete (or rename) the Models folder and create a new one called ViewModels if that helps.
Regardless of what you do, you’ll ultimately call #model and not #viewmodel at the top of your pages.
Another similar example would be DTO classes. DTO classes are nothing more than regular classes but they are suffixed with DTO to help people (programmers) differentiate between all the other classes (including View Models).
In a recent project I’ve worked on, that notion wasn’t fully grasped by the team so instead of having their Views strongly typed to Models, they would have their Views strongly typed to DTO classes. In theory and in practice everything was working but they soon found out that they had properties such as IsVisible inside their DTO’s when in fact; these kind of properties should belongs to your ViewModel classes since they are used for UI logic.
So far, I haven’t answered your question but I do have a similar post regarding a quick architecture. You can read the post here
Another thing I’d like to point out is that if and only if your Service Layer plans on servicing other things such as a Winform application, Mobile web site, etc...then your Service Layer should not be receiving ViewModels.
Your Service Layer should not have the notion of what is a ViewModel. It should only accept, receive, send, etc... POCO classes.
This means that from your Controller, inside your ActionResult, once the ModelState is Valid, you need to transform your ViewModel into a POCO which in turn, will be sent to the method inside your Service Layer.
In other words, I’d use/install the Automapper nugget package and create some extension methods that would convert a ViewModel into a POCO and vice-versa (POCO into a ViewModel).
This way, your AddNewPerson() method would receive a Person object for its parameter instead of receiving a PersonViewModel parameter.
Remember, this is only valid if and only if your Service Layer plans on servicing other things...
If that's not the case, then feel free to have your Service Layer receive, send, add, etc...ViewModels instead of POCOs. This is up to you and your team.
Remember, there are many ways to skin a cat.
Hope this helps.

Has anyone got a good example of unit of work with multiple repositories that is not using EF?

I am about to implement the unit of work pattern with MVC3.
I have:
MVC Service Layer (BLL)
Repository Layer
Multiple types of databases
I want my service layer to get the IUnitOfWork passed to it by my IOC container. (This is easy and not part of this question).
So my service layer will do this: (Note: this is pseudo code)
(using unitOfWork)
{
ProductSqlRepository.Update();
PersonOracleRepository.Update();
IUnitOfWork.Commit();
}
All the samples I can find use EF. Whilst one of my repositories might use EF others may not.
My question is then, can I use the Unit of work pattern across multiple repositories that may sit above different types of databases (ie... EF, Oracle... other)
So, if I want to wrap an update to a SQL database and an oracle database in the ONE unit of work call, is the unit of work the way to do it.
As I mentioned, all examples I can find are for 100% EF solution, I need to mix and match.
Thanks
RuSs
The UnitOfWork scope is essentially already defined in MVC since all of your logic is done within an action. The common pattern I've seen (and what I ended up doing in my app) is to handle your unit of work via an attribute you register globally to your app and handle setting up whatever unit of work logic (transactions etc) you need to in the OnActionExecuting and OnActionExecuted of that attribute. There are a few caveats like making sure that the action isn't a child action and checking for ModelState errors but there are examples of this online. Also note that if you do not use viewmodels exclusively in your views, you may run into issues with certain frameworks lazy loading data in a view after your unit of work scope has closed.
My project used nHibernate and I used these two posts as inspiration for my implementation. Hopefully they'll give you a few ideas as well.
http://ayende.com/blog/4809/refactoring-toward-frictionless-odorless-code-what-about-transactions
http://slynetblog.blogspot.ca/2011/04/lightweight-nhibernate-and-aspnet-mvc.html

Strategy to refactor when too many dependencies injected into service or controller

I have an ASP.NET MVC 1 application that uses NHibernate and Castle Windsor for IoC. The controllers have service classes injected, and these service classes handle all the logic and actions required by the app. The service classes have repositories injected. Each repository handles a single object. Objects are mapped to DB table via NH. I have tried to keep a one to one relationship between services and controllers, but some services are used in more than one controller.
The problem is that some services now have dependencies on 10-15 repositories. The system has an invoicing component for example, where certain actions depend on users, customers, work orders, work order line items, invoices, invoice line items, taxes, etc.
What strategies do people used to refactor effectively when it comes to dependency overload? I'm thinking of splitting one service into many services and to remove the 1-to-1 attempt between services and controllers. But then dependencies at the controller level will increase. Splitting one controller into many controllers is possible with the prior suggestion, but I don't believe that's done unless you break views into partial views? I realize this is a broad question, but I'm more looking for guidance than exact answers. Feel free to provide links to articles or examples of similar refactoring.
You should refactor to Facade Services, which involves sliding in a new layer of more coarse-grained services that orchestrate the finer-grained services. Currently your Controllers are doing too much fine-grained work.
FWIW chapter 6 of my book contains an example of this process and it also touches on some of the mental exercises you can do to identify the appropriate clusters of services to be grouped.
Keep in mind that a particular service can be a member of more than one cluster. That basically just indicates that this is a central service in the application.
Your repository approach is flawed. Instead of having a repository for each and every entity type in your application, you should focus on your root entities. Pick a few entities that are the top level entities in your application and build your repositories around them. E.G. work order line items likely don't need their own repository, as they can't exist on their own without a work order.
Another thing you've likely created in your design is a very anemic domain layer. So your entities are pretty much just POCO objects, while all of the business logic is contained in your service layer. Consider moving some or most of that logic into the domain.

MVC DDD: Is it OK to use repositories together with services in the controller?

most of the time in the service code I would have something like this:
public SomeService : ISomeService
{
ISomeRepository someRepository;
public Do(int id)
{
someRepository.Do(id);
}
}
so it's kinda redundant
so I started to use the repositories directly in the controller
is this ok ? is there some architecture that is doing like this ?
You lose the ability to have business logic in between.
I disagree with this one.
If business logic is where it should be - in domain model, then calling repo in controller (or better - use model binder for that) to get aggregate root and call method on it seems perfectly fine to me.
Application services should be used when there's too much technical details involved what would mess up controllers.
I've seen several people mention using model binders to call into a repo lately. Where is this crazy idea coming from?
I believe we are talking about 2 different things here. I suspect that Your 'model binder' means using model simultaneously as a view model too and binding changed values from UI directly right back to it (which is not a bad thing per se and in some cases I would go that road).
My 'model binder' is a class that implements 'IModelBinder', that takes repository in constructor (which is injected and therefore - can be extended if we need caching with some basic composition) and uses it before action is called to retrieve aggregate root and replace int id or Guid id or string slug or whatever action argument with real domain object. Combining that with input view model argument lets us to write less code. Something like this:
public ActionResult ChangeCustomerAddress
(Customer c, ChangeCustomerAddressInput inp){
c.ChangeCustomerAddress(inp.NewAddress);
return RedirectToAction("Details", new{inp.Id});
}
In my actual code it's a bit more complex cause it includes ModelState validation and some exception handling that might be thrown from inside of domain model (extracted into Controller extension method for reuse). But not much more. So far - longest controller action is ~10 lines long.
You can see working implementation (quite sophisticated and (for me) unnecessary complex) here.
Are you just doing CRUD apps with Linq To Sql or trying something with real domain logic?
As You can (hopefully) see, this kind of approach actually almost forces us to move towards task based app instead of CRUD based one.
By doing all data access in your service layer and using IOC you can gain lots of benefits of AOP like invisible caching, transaction management, and easy composition of components that I can't imagine you get with model binders.
...and having new abstraction layer that invites us to mix infrastructure with domain logic and lose isolation of domain model.
Please enlighten me.
I'm not sure if I did. I don't think that I'm enlightened myself. :)
Here is my current model binder base class. Here's one of controller actions from my current project. And here's "lack" of business logic.
If you use repositories in your controllers, you are going straight from the Data Layer to the Presentation Layer. You lose the ability to have business logic in between.
Now, if you say you will only use Services when you need business logic, and use Repositories everywhere else, your code becomes a nightmare. The Presentation Layer is now calling both the Business and Data Layer, and you don't have a nice separation of concerns.
I would always go this route: Repositories -> Services -> UI. As soon as you don't think you need a business layer, the requirements change, and you will have to rewrite EVERYTHING.
My own rough practices for DDD/MVC:
controllers are application-specific, hence they should only contain application-specific methods, and call Services methods.
all public Service methods are usually atomic transactions or queries
only Services instantiate & call Repositories
my Domain defines an IContextFactory and an IContext (massive leaky abstraction as IContext members are IDBSet)
each application has a sort-of Composition Root, which is mainly instantiating a Context Factory to pass to the Services (you could use DI container but not a big deal)
This forces me to keep my business code, and data-access out of my controllers. I find it a good discipline, given how loose I am when I don't follow the above!
Here is the thing.
"Business Logic" should reside in your entities and value objects.
Repositories deal with AggregateRoots only. So, using your repositories directly in your Controllers kinda feels like you are treating that action as your "service". Also, since your AggregateRoot may only refer to other ARs by its ID, you may have to call one more than one repo. It really gets nasty very quickly.
If you are going to have services, make sure you expose POCOs and not the actual AggregateRoot and its members.
Your repo shouldn't have to do any operations other than creating, retrieving, updating and deleting stuff. You may have some customized retrieve based on specific conditions, but that's about it. Therefore, having a method in your repo that matches one in your service... code smell right there.
Your service are API oriented. Think about this... if you were to pack that service in a .dll for me to use, how would you create your methods in a way that is easy for me to know what your service can do? Service.Update(object) doesn't make much sense.
And I haven't even talked about CQRS... where things get even more interesting.
Your Web Api is just a CLIENT of your Service. Your Service can be used by another service, right? So, think about it. You most likely will need a Service to encapsulate operations on AggregateRoots, usually by creating them, or retrieving them from a repo, do something about it, then returning a result. Usually.
Makes sense?
Even with "rich domain model" you will still need a domain service for handling business logic which involves several entities. I have also never seen CRUD without some business logic, but in simple sample code. I'd always like to go Martin's route to keep my code straightforward.

Architecting ASP.net MVC App to use repositories and services

I recently started reading about ASP.net MVC and after getting excited about the concept, i started to migrate all my webform project to MVC but i am having a hard time keeping my controller skinny even after following all the good advices out there (or maybe i just don't get it ... ).
The website i deal with has Articles, Videos, Quotes ... and each of these entities have categories, comments, images that can be associated with it. I am using Linq to sql for database operations and for each of these Entities, i have a Repository, and for each repository, i create a service to be used in the controller.
so i have -
ArticleRepository
ArticleCategoryRepository
ArticleCommentRepository
and the corresponding service
ArticleService
ArticleCategoryService ...
you see the picture.
The problem i have is that i have one controller for article,category and comment because i thought that having ArticleController handle all of that might make sense, but now i have to pass all of the services needed to the Controller constructor. So i would like to know what it is that i am doing wrong. Are my services not designed properly? should i create Bigger service to encapsulate smaller services and use them in my controller? or should i have an articleCategory Controller and an articleComment Controller?
A page viewed by the user is made of all of that, thee article to be viewed,the comments associated with it, a listing of the categories to witch it applies ... how can i efficiently break down the controller to keep it "skinny" and solve my headache?
Thank you!
I hope my question is not too long to be read ...
This is the side effect of following the Single Responsibility Pattern. If each class is designed for only one purpose, then you're going to end up with a lot of classes. This is a good thing. Don't be afraid of it. It will make your life a lot easier in the long run when it comes to swapping out components as well as debugging which components of your system aren't working.
Personally, I prefer putting more of my domain logic in the actual domain entities (e.g. article.AddComment(comment) instead of articleCommentService.AddComment(article, comment)), but your approach is perfectly fine as well.
I think you are headed in the right direction. The question is how to instantiate your services? I'm no MVC.NET guru, but have done plenty of service oriented Java projects and exactly the pattern you are discussing.
In Java land we would usually use Spring to inject singleton beans.
1) You can do the same thing in .NET, using dependency injection frameworks.
2) You can instantiate services as needed in the method, if they are lightweight enough.
3) You can create static service members in each controller as long as you write them to be threadsafe, to reduce object churn. This is the approach I use in many cases.
4) You can even create a simple, global service factory that all controllers access, which could simply be a class of singletons.
Do some Googling on .NET dependency injection as well.

Resources