Header background image for AlwaysMoveForward.com
Software

My MVC Experiment Part 5

By Arthur Correa • Author

myself to do ASP.Net MVC, and was pleasantly surprised at how much I liked it.  I decided to do it as a multi-blog site just to make life interesting, and then used LINQ and realized that it made life pretty easy.

Ok, so I need some place to put my core business logic and my data access code.  Well I'm using MVC so I could just put my business logic in the Controller, but in my last post I explained why I didn't like that.  So I want to put my business logic in a Manager class. 

First I define a Service layer.  Essentially it decouples entities from the Input Interface (whether that be Web app, web service, client app, another internal object, whatever needs to call into that domain logic to do work).   An important thing to note is that these Service classes are stateless.

Ok, those are definitely staying.  I need my Business Logic after all.  But what about my Gateway?  The purpose of the Gateway is to encapsulate all of the logic neccessary to interact with the data repository.  Toss an interface on top of it and you can easily swap out access methods in and out with the help of a Factory.  You could switch from LINQ to NHibernate or whatever pretty easily.

Now I've seen implementations where the data access logic is in the Service layer as well.  It works, if you're only ever using a single data access method you'd probably be fine.  But with just a little extra work you can break it out and have the flexibility to switch if you want to in the future (from my experience, if you plan for it you'll never do the switch, but if you don't plan for it you'll need to do it tomorrow).

So since its not that much more work, and because I plan to implement other data access methods besides LINQ (remember I plan to use this as a learning platform so I'll be implementing NHibernet with this as well), then I'll keep this class in place.

So what does my total infrastructure look like?  More or less like this

So lets walk through an example for a user login

  1. The UserController instantiates a UserService object and calls its Login method to do all the work. 
  2. The Login method does a few things.  Encrypts the password passed in to th e method, then instantiates a UserGateway and calls its GetByUserIdAndPassword with the user id and encrypted password.
  3. The User entity gets instantiated and populated by LINQ and is returned to the UserService::Login method.
  4. The UserService::Login method puts the returned user on the current threads principal propery.
  5. The User is returned to the controller.

So now that I've gotten through that stuff.  Now we're onto the actually MVC portion of our program.