Separation of Concerns with Generics for IoC - asp.net-mvc-3

My project is organized as follows
ASP.NET MVC 3 WebApp
Domain.Core - Interfaces [library]
Domain.Core.Entity - Entities [library]
Infrastructure.Core - Implementation of Interfaces [library]
Infrastructure.IoC - Uses Unity as a means of achieving Inversion of Control [library]
The predicament is as follows:
If I were to add a generic method to an interface in my Domain.Core, such as the following, I get a compile error that asks me to add a reference to Domain.Core.Entity in the Infrastructure.IoC project.
T Get<T>(int Id) where T : EntityBase, new();
T can be a class EntityBase or Blog which inherits from EntityBase or a few other entities that all inherit from EntityBase. The idea is to return an entity based on what child class is provided so that the child class is loaded with the default data that is required for all classes that implement EntityBase.
So, the question is two fold:
Is it better to not reference the Domain.Core.Entity project in the IoC project and keep things clean?
How would I achieve something like the above without having to muddy the cleanliness of references?
Thank you.
Note: I went through a few of the questions here to search for this topic but didn't see any. If you do see it, then let me know and I will delete this question.

With Dependency Injection, it's best to have a single component with the responsibility of composing all the various collaborators. This is the third party in Nat Pryce's concept of Third-Party Connect, or what I call the Composition Root. In the architecture outlined above, this responsibility seems to fall on Infrastructure.IoC, so given this structure, there's nothing wrong with adding a reference from Infrastructure.IoC to Domain.Core.Entity - in fact, I would find it more surprising if it were not so.
However, as an overall bit of feedback, I think it's worth considering what benefit is actually being derived from having a separate Infrastructure.IoC library. The entry point of that application (the ASP.NET MVC application) will need to have a reference to Infrastructure.IoC, which again must have a reference to all libraries in order to compose them. Thus, the ASP.NET MVC application ends up having an indirect reference to all other libraries, and you might as well merge those two.
(Technically, you can decouple the various libraries by relying on some sort of late binding mechanism such as XML configuration or Convention over Configuration, but the conceptual responsibility of Infrastructure.IoC is going to remain the same.)
For more information, you may want to read this answer: Ioc/DI - Why do I have to reference all layers/assemblies in entry application?

Why split the Domain.Core from Domain.Core.Entity? And why split Infrastructure.Core from Infrastructure.IoC?
I think you can get away with a 3 project structure:
Domain - has no dependencies on the other 2 projects. May contain entities and interfaces.
Infrastructure - contains interface implementations and the Unity container. Depends only on Domain project.
MVC - depends on both Domain and Infrastructure.
If you are worried about programming against concrete classes instead of interfaces, give the classes in the Infrastructure project a different namespace. You should then only have to use that namespace maybe a couple of times (in Global.asax or bootstrapper) if at all.
This way it is very clear what projects depend on what. Since you are using unity, this is a form of onion architecture. If you find later that you should split Infrastructure or Domain out into more than 1 project, you can refactor.
IMO, dependencies only get muddy or unclean when you have references like System.Web.Mvc or Microsoft.Practices.Unity in your domain project(s). Like Mark says in his answer, the outer layers of your "onion" will have dependencies on the inner layers, there's not much you can do to avoid that. But try to make the domain concentrate on its core business, avoiding as much detail of how it will be used in a UI as possible.

Related

Naming DTO and Entity classes

I have two sets of classes in my spring application - DTOs and Entities.
After reading Clean Code by Uncle Bob, I have got hooked on to naming things right more than ever before.
I sat down refactoring one of my Spring projects and I am not sure if adding DTO suffix for DTO classes is the right thing to do. If not, then how do you differentiate between DTO and Entity classes. I do use Service and Repository suffixes for my service classes and repository interfaces.
Merely keeping them under different packages with same names is not helpful esp. when they are to be used in same scope.
Note: Not sure if this is a precise question to be asked on Stackoverflow.
If you read Core J2EE Patterns, 2nd Edition, it is called Transfer Object with all the sample codes having the TO suffix. You can also have a look at Oracle's Core J2EE Patterns site.
To sum up: You should use either DTO or TO as a suffix to any transfer object you use in your business tier.

MVC / Repository Pattern - Architecture

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!

How to dynamically manage project dependancies

We are writing a new set of services and have decided to make them share a common interface... calling it a BaseService. The idea is that whenever anyone wants to develop a new service in our organization, they should be just able to extend and use this BaseService.
We have written a few other classes which also form a part of this base jar, it does things like handle transactions and connect to database using hibernate etc.
Right now all the services that extend the BaseService are a part of the same project (Eclipse + Maven), and some of the services are dependent on each other, but because they are in the same project we don't have a problem with dependencies.However, we expect 40-50 services to be written which would extend base service and would also be interdependent.
I am worried that the size of the base project would be huge and that just because when someone has to use one service they might have to depend on my base jar which has 50 services.
Is there a way that we can make some projects dynamically dependent on others?
Lets say I have a service A which depends on service B, when I build/compile Service A,it should be able to realize that it has a dependency on service B and automatically use the Service B jar.
I have heard of OSGi, will it solve my problem or is there a way I can do it with Maven or is there a simpler solution ?
Sorry about the long post !
Thanks in advance for your suggestions
It doesn't make any sense to "dynamically" manage project dependencies, since build dependencies are by definition not dynamic.
Your question, at least for the moment, seems to be entirely about how to build your code rather than about how to run it. If you are interested in creating a runtime system in which new service implementations can be dynamically added then OSGi may be the solution to look at. An extra advantage here would be that you could enforce the separation of API from implementation, and prevent the implementing services from invalidly depending on parts of your core module that you do not want them to have visibility of.
You could also use OSGi to manage evolution of your core service API through versioning; for example how do you communicate the fact that a non-breaking change has been made to the API versus a breaking change etc.
I would say there are two options depending if i understand your question correct. First one. You have already defined an interface (java term) and now you have different implementations of that. The simple solution for Maven would be to a have a module which is called for example: service-api and than this will be released and can be used by others as dependencies. On their side they simply implement the interface. No problem with the dependencies. If you are more talking about OSGi than you should take a look to maven-tycho.

why a ioc framework for MVC 3?

After plenty of reading, I still don't understand Unity for MVC 3.
Specific points
Why use it? I can create a controller that in its constructor, it takes a new EF context for testing.
How? I keep seeing bits are parts, but is there an end to end walk through on implementing Unity on MVC 3 (Live)? There seem to be plenty on Beta and RC, but the code always seems to have a problem on live frameworks.
Currently this is not impacting my unit testing, since my controllers have overloaded constructors, as does my EF context.
If you have a small project, you may not benefit from IoC.
Lifetime management if a plus for me. I don't have to dispose a repository (or service layer) in every controller. It thins out my code and creates the object for me. In addition, I know I have a clean separation in case I ever need to change things. It almost forces me to. I use for example IRepository that is backed by entity framework. For testing I use a fake IRepository implementation. So sure, I could manually create it in my application but this leads to some bad practices in larger projects and I lose the benefits of having the interface.
I have a basic demo for a super short talk I did recently on this for (15 minutes) mvc and unity for dependency injection using the unity.mvc3 nuget package:
http://completedevelopment.blogspot.com/2011/12/using-dependency-injection-with-mvc.html
Btw. Dependency Injection in .Net - best book on the subject without a doubt.
It's very useful for wiring up all your dependencies, handling life cycle of your objects, error handling, transaction handling, testing purposes and ...
All of above point are advantages of using an IoC framework, but I strongly recommend using Ninject. it has a very friendly DSL for binding modules, has out of box library and extensions for ASP.NET MVC and is an open source lightweight DI framework.
It has also many extensions.

How to architect MVC 3, EF, ViewModels, AutoMapper, POCO, Repository and Unit of Work in n-tiered project?

I have been reading countless articles about how to architect a new MVC 3 application using best practices.
90% of the articles combine the EF EDMX files into the same project as the MVC app. Those that do seperate these items into their own projects don't clarify which project each goes into and what references each project has. Usually they consist of code snippets that are great to teach how to do a specific function, but don't tell me how to architect the solution.
I believe that I need at least 5 projects in my solution. Can anyone tell me if I have the correct layout here?
Data Access Layer - Contains the EF EDMX files. (Perhaps the DBContext auto-generated code?)
Business Layer - Contains the IRepository and Repository classes, UoW classes, as well as the business logic for the domain. - Contains reference to DAL.
ViewModels - Contains the viewmodels that will use AutoMapper to go between my DAL and the presentation layer. - Contains reference to DAL.
MVC 3 App - Standard MVC 3 app. Contains references to the BusinessLayer and the ViewModels projects.
Test - Unit testing.
Does this look right? Can anyone point me to a good article that uses n-tiered development with ViewModels, AutoMapper, Repository patterns and EF4?
When looking at what project to put something in, it helps to think about how you are going to be deploying your code. Put code that will ship together in the same project and then use namespaces to separate it out logically into separate tiers. For most of the projects I work on it tends to be pretty simple with 3 projects.
Business Layer
Domain/Business Model and Services
Data Access Layer
MVC App
View Models
Automapper
Controllers
Views
Tests
Unit tests
I like the following
Domain - contains models and ViewModels
Services -business logic and viewmodel hydrating (ie population) code
Contracts or interfaces - repository interfaces, unit of work, IContext, and ICache
Web site
DataAccess - concrete implementation of entity framework
Some include their AutoMap code directly as an action filter as an attribute inside the web project. My automap code is done in the services project (but again this is up to you) unless I can use the attribute to do it in the controller.
btw see Jimmy's nice attribute here:
http://lostechies.com/jimmybogard/2009/06/30/how-we-do-mvc-view-models/
What you have outlined above is fine as well though. This is a very subjective matter. My general recommendations are that 'if someone can open a project and have an idea where to look for something, you are likely doing it correctly'
The way I usually do it:
Model project - Contains the model generated from the db and the context.
POCOs project - Contains the Business entities
Controller project - similar to your repository
MVC3 project - front end, INCLUDING view models and repository classes that include automapper equivalencies.
Unit tests
Architecture is technology independant, whether you are using EF, Hibernate, MVC, webforms etc... And you usually combine patterns. Besides is mostly depends on each particular project.
Regarding to best practices, when talking about EF, I can't link you to the source I use because I use a book. However I'll link you to the author's blog, it's Julie Lerman's Programming Entity Framework.

Resources