MVC / Repository Pattern - Architecture - asp.net-mvc-3

I have a project in which I am using NHibernate and ASP.Net MVC. The application is intended to allow users to track certain data and then produce views of statistics based upon the data entered. The structure of my application thus far looks something like this:
NHibernate Layer: Contains Repository<T> and UnitOfWork classes, as well as entity mapping definitions.
Core/Service Layer: Contains generic EntityService class. At the moment, this simply defines transaction scope via IUnitOfWork and interfaces with IRepository to provide higher-level data access services.
Presentation Layer (MVC Application): Not yet implemented, but contains the usual stuff plus dependency injection.
I have a couple of questions:
Is it poor design to allow my MVC application to handle dependency injection for ALL layers? For example, as well as dependency injection of EntityService instances into controllers, it will handle the dependency injection of IRepository into the EntityService classes. Should the service layer handle this itself, even though this would mean performing dependency injection in two distinct places?
Where should I produce my statistics? This business logic doesn't seem to belong in my service layer, which, at present, only contains entity type definitions and an interface for modifying and accessing entity properties. I have a few thoughts on this, but I'm not sure which I like best:
Keep my service layer as is and create a separate Statistics project - this is completely independent of the entity types for which it will be used, meaning my MVC controllers will have to pass raw numerical information between my business entities and my (presumably static) statistics classes. This is quite a neat separation but potentially means a lot of business logic still remaining in the presentation layer.
Create a Statistics project; however, create a tight coupling between the classes in this project and my business entities. For example, instead of passing a Reading object's values into a method, I will pass the entire object (or define them as extension methods). This will shift business logic out of my MVC app but the tight coupling seems a bit messy.
Keep all of my business logic inside my service layer. Define strongly-typed subclasses of EntityService, so my services contain both entity-specific business methods and data storage methods, while keeping the entity classes themselves as pure data containers. Create a separate Statistics project for any generic statistical processing and call its methods via my derived service classes. My service classes effectively merge business functions with the storage functionality provided created by IRepository<T>.
I am erring toward the third option but does anyone have any thoughts? Alternative suggestions?
Thanks in advance!

Preliminary observation:
I like the way in which you described your project, I just didn't get why your Data Access Layer (DAL) is called NHibernate Layer: it is odd with all the rest in which you didn't use technology name to describe a logical layer (correctly). So I suggest you to rename it DAL, and use it to abstract your app from NHibernate.
My opinions about your questions:
Absolutely no. It is good to apply Dependency Injection to All Layers. A couple or reasons for which it is good:
1.1 Testing: you can mock DAL interfaces and do unit test Service Layer w/o DAL using another DI config file. In the same way you can mock Service for Web Controllers layer and so on.
1.2 Different DAL implementations: suppose you need different DAL implementation (NOSQL, SQL or LINQ instead of NHibernate, etc..) technologies for different deployment of you project or to scale in the future. You can do that easily maintaining different DI config files.
You can have the same layer deployed in different projects. In the same way you can have a project containing different layers. I think their relation is orthogonal: project is describing a physical (development time and run time) implementation. Layers are logical. So initially I would keep it simple with the third option.
I just don't understand why you saying the following regarding this option:
Create a separate Statistics project for any generic statistical
processing and call its methods via my derived service classes. My
service classes effectively merge business functions with the storage
functionality provided created by IRepository.
I see Statistics as one or more services so you can implement it as namespace with classes inside your Service Layer. And, as any other service, you can inject DAL Repository classes. And, as any other Service/DAL, the Model classes can be shared between different Services and DAL classes.
StatsService.AverageReadingFor(Person p, DateTime start, DateTime end) sounds good.
There are several implementation options:
Using underlying repository features (for example: SQL avg function)
Using Observer Pattern which is implementable also using Dependency Injection
Using Aspect Oriented Programming. See that Spring.Net chapter as an example.
If you have more than one Service Layer instance (more than one server) than 2 and 3 must be adapted for out of process communication using a messaging system.

Just an update - Regarding my second question, I have decided to define an IStatsService<T> which expects an IEntityService<T> to be passed into its constructor. I'll use this for generic statistical processing of business entities and create further interfaces that implement IStatsService<T> where I need more type-specific information.
Hopefully this will help someone who has been scratching their head about a similar problem!

Related

how to use spring 3.0 without service?

I am using spring 3.0 with annotation which i am creating dao interface , then dao implementation class,
then creating service interface and then creating service implementation class.
and using object of service implementation into controller. this process is too lengthy.
can i use only dao class and directly use it in controller?
#service
#controller
public class MyController { ... }
You can but you really really really shouldn't. If you have any plans of putting this code into production, then you need to keep your layers well defined. This is because each layer has a different responsibility.
Your DAO layer is responsible for all database access. It doesn't care what object you want, what you want to do with it, and when you want it done. It only cares about how it's done.
Your Service layer is responsible for what you want to do to your objects. It contains all of your business logic, convenience methods and may use multiple DAO's inside a single service. Your service layer is where you handle your database transactions as well.
Your controller layer is responsible for how you want to show your data to the user. It only contains services and minimal logic concerned with how to display the data returned by your service layer.
I think there are 2 distinct questions being asked here :
Is it really necessary to have all three layers : web layer, service layer, and DAO ?
and :
Do Spring beans necessarily need to implement and interface and to bve (auto)wired by interface rather thant concrete class ?
The answer to both is the same : it is not a necessity, but it is strongly recommended for anything other thant trivial projects.
For the first question, yes it is better so separate concerns in different layers. However I must admint that my controllers sometimes access the DAOs directly for simple read-only tasks in some projects. Sometimes the service layer seems like too much when all it does is to map the DAO methods. However I always use a service layer for transactional business logic that actually modifies the data.
For the second question : Spring can, without problem, instantiate and inject beans that don't implement any interface. However you will start to have problems if you use more advanced stuff linked to aspect-oriented programming, the most common being the #Transactional annotation. In this case Spring has to create proxies to your objects, and it is all simpler to create proxies of interfaces. Ohterwise it has to manipulate bytecode and it introduces limitations.
Perhaps more importantly, "programming to an interface" is a good practice regardless if you are using Spring or not, or even Java or anothrer language. A simple google search will bring up many good articles on this, or SO questions such as this one.
So again, while you can live well without both things in the short term, both will make your life much better in the long term.

Spring - dependency injection benefits

I'm a newbie to Spring Framework and of course first thing comes to mind about spring is dependency injection. Now i could be wrong since i just started learning about Spring framework (esp. about dependency injection) but i think that dependency injection of beans to said objects is not meant for transaction data. Since the bean definition is for example defined in the spring.xml (a blue print) it is not meant for transactional data but rather for static and small amount of data. I don't see that there's any way to inject thousands of transactional objects into another object using dynamic XML (created during runtime).
So did i get this right? If that is so what's the real benefit of dependency injection?
There are several benefits from using dependency injection containers rather than having components satisfy their own dependencies. Some of these benefits are:
Reduced Dependencies
Reduced Dependency Carrying
More Reusable Code
More Testable Code
More Readable Code
These benefits are explained in more detail here.
You are right, transactional data (eg: data that represents a table row) don't normally be injected declaratively. Spring DI (dependency injection) commonly use to handle collaboration between multiple classes.
Common examples I've seen is along with DAO (data access object) and MVC (model view controller) pattern. In enterprise environment it's common to have a project with dozens or hundreds of database tables -- hence dozens / hundreds of DAO classes which get injected into controller classes.
If you don't use DI, you need to conciously manage which DAO should be created first, and which DAO should be injected into which controller etc. (this is a nightmare)
Code refactoring is (should) be a common thing as well. Business requirement always changes constantly. Without DI one simple refactoring could result in a massive and tricky untangling of 'which class depends on what and where'
Of all the articles I've read about the dependency injection, this is by far the best.
If you are using Spring for DI, I would suggest you read about #primary annotation. Spring makes it even easier to choose the implementation you want(from multiple implementations) for a given service. This article is good.
Dependency Injection and Inversion of Control change the control flow adding to a specific component the responsibility to manage de dependency graph and manage how it will be connected. The result is a great decoupling between dependant and dependency, improving the code maintainability, application reliability, and testability.

What is the purpose of utility layer and how is this linked with other layers in a web application architecture?

I am new to Java EE architecture (trying to do some reading on this - please suggest good sources).
When we use MVC pattern, the DAO layer consists of classes that contain methods to access the database. Similarly service layer contains classes that make use of methods from DAO classes and have some business logic. I see in some projects that Util classes are used and they contain methods that perform some work for the service layer classes.
What is the exact purpose of this Utility layer? Can it contain getters and setters from Spring dependency injection?
There is no "utility layer". Constructions like like MyMagnificentMailer are just a different kind of service. I am not sure if you actually separate the domain objects from DAOs (or other forms of abstraction for storage ), but just like domain object can contain and interact with other domain object, same way your Authentication service can interact with Mailer and vice versa.
There is not rule saying, that real services have to be build on top DAOs.

Regarding DDD Structure and Layering.

Folks,
Apologies if this has been covered in another thread, but I have searched ddd and mvc articles and have not found a straightforward answer.
I am hoping to apply a DDD approach to the architecture of my MVC projects. Please correct me where I am wrong.
All MVC controller actions that involve hitting the domain model will initially hit
and application service layer.
The application service layer here acts as a facade between presentation and the domain.
Any requests from the application service later that clearly involve discrete domain aggregates will perform fetch or modify operations on aggregate roots using repositories. Each aggregate root will have its own repository.
so the application service layer must be injected with any/all repositories required by the domain.
Where an operation may involve multiple aggregates or requires logic that does not fit neatly into one aggregate, the application service will call a domain service to carry out operations across aggregates.
This does not seem right to me.
My confusion is that from a DDD perspective Im not sure whether for example aggregate roots should perform their own persistance i.e. the aggregate gets injected with a repository and then persists/fetches itself or whether as above the application service layer uses repositories to act on or fetch aggregates?
Also if the application service layer is injected with all repositories, does the domain service that the application service layer calls also need repositories injected?
Im keeping CQRS out of this at this point. I want to get the layering and the relationship between services and aggregates sorted out first.
Thanks for any advice.
All MVC controller actions that involve hitting the domain model will
initially hit and application service layer. The application service layer here acts as a facade between presentation and the domain.
There's debate over that but I would consider carefully whether that additional layer is needed or not. It adds a lot of boilerplate code and degrades maintainability - as someone pointed out recently, when you separate things that change for the same reasons (ie your service methods and the corresponding domain methods), you have to make changes in many different places in the system.
On the other hand, you could need that service layer to map your domain objects to DTOs but there again, it could be done directly in the Controller and nothing forces you to use DTOs in the presentation layer.
My confusion is that from a DDD perspective Im not sure whether for
example aggregate roots should perform their own persistance i.e. the
aggregate gets injected with a repository and then persists/fetches
itself or whether as above the application service layer uses
repositories to act on or fetch aggregates?
It's usually considered bad practice to have aggregate roots manage their own persistence because it breaks persistence ignorance and violates the Single Responsibility Principle. If you do that, your aggregate root class now has 2 reasons to change, 2 reasons to break the code, it is less maintainable, etc.
You should instead delegate the responsibility of saving the aggregate root in its repository to an object that will be aware of the application execution context (for instance, a Controller or an object in the Application layer).
Also if the application service layer is injected with all
repositories, does the domain service that the application service
layer calls also need repositories injected?
Yes, I think it pretty much makes sense especially if the domain service heavily relies on the repository.

Architecting ASP.Net MVC 3 with EF

I'm trying to architect my MVC web project and I'm running into a bit of a problem.
I am using EF4.1. I've created a DataAccess project with the EDMX file. Then I use the dbContext generator to make my POCO .tt classes.
As it is right now, my Business logic layer can access the POCO classes just fine, but the presentation layer cannot.
I think that I'm supposed to create another level of abstraction and put the dbContext .tt files into their own project so that both the BusinessLogic layer and the Presentation layer can access the POCO classes, but only the BusinessLogic has access to the entity framework. The presentation layer shouldn't need to know anything about EF.
Something like this...
POCO Classes - DataAccess
| |
|---------Business Logic
| |
|_________Presentation
Am I on the right track here, and if so, do I simply cut/paste the .tt files into the new project or is there a way to force the dbContext add-on to create these in my other project?
Your presentation layer doesn't have to know anything about the EF. Just reference that project from your presentation layer to access the models.
However - your presentation layer shouldn't ideally be using any of those POCO models. They should be using ViewModels. I dont necessarily believe in the DTOs here as DTOs have a specific purpose. Your repository/data access can return models but generally those get returned to a service layer. The service layer then would return your ViewModel representation to your controller.
This sets you up nicely for dependency injection as well, since into your controller you just inject your service layer. Into your service you can inject then any repositories you need, and so on.
Ironically I think I may be working on a book for this exact subject shortly : )
Consider sending Data Transfer Objects between your Business Logic and Presentation layers. This would allow you to shape the data for your views and and prevent information from leaking into the Presentation layer (e.g. if you have a field in your POCO that is needed for your business logic but doesn't need to be available in your Presentation layer).
The question is, how would you move data to and from the
presentation layer? Put another way, should the presentation layer
hold a reference to the domain model assembly? (In an Entity Framework
scenario, the domain model assembly is just the DLL created out of the
EDMX file.)
From a pure design perspective, DTOs are a solution really close to
perfection. DTOs help to further decouple presentation from the
service layer and the domain model. When DTOs are used, the
presentation layer and the service layer share data contracts rather
than classes.
A layer of DTOs isolates the domain model from the presentation,
resulting in both loose coupling and optimized data transfer.
If you go this route, also check out Automapper to help with mapping your DTOs to POCOs and vice-versa.
So there are several ways to structure your project. What you are referring to is one way, in which you share poco's between all layers.
Another way is to have your POCO's be in the data and business layer, then create a similar object model that's shared between UI and business layer. Finally, you might also create a third model for the UI only called teh ViewModel.
It all really depends on your needs. If your object model is very complex, then you might need to simplify it with ViewModels.

Resources