Architecture Layering Part II

Back awhile ago I made this post on Architecture layering.

Having a service layer in a ASP.NET MVC is a great thing!

Initially I was wrapping Actions with transactional attributes, making calls to the Dao objects, etc… Sure, the dao objects are being injected by my IoC container (Windsor) – which by the way, is very sweet, it’s so transparent that I forget who it creating the objects… I just use the interface… (that is another story)

I show a simple example below, but this sample doesn’t capture where I’ve been able to move business logic back into services – simplifying the controllers.   (Also, it cuts back on any duplication)

Simple example:

MyCustomerController

private readonly ICustomerDao CustomerDao;

ctor : MyCustomerController(ICustomerDao CustomerDao){ this.CustomerDao = CustomerDao;}  //injected

Then on a save:

[Transaction]
public ActionResult Save(string id)
{
     …  CustomerDao.Save(Customer);
}

Instead I’ve moved this into a service layer – now the controllers know nothing about the data access layer:

public class CustomerService : ICustomerService
{
    private readonly ICustomerDao CustomerDao;
    public CustomerService(ICustomerDao CustomerDao){ this.CustomerDao = CustomerDao;}  //injected

    public void SaveCustomer(Customer customer)
    {
         using(ITransaction tran = NHibernateSession.Current.BeginTransaction())
         {
                try….
                CustomerDao.Save(Customer);
                tran.Commit();
                …

         }
    }
}

That is our service – it handles all transactions – where needed – in conjunction with the Dao objects

Now the controller gets an injected CustomerService rather than a CustomerDao.  Notice the Transaction attribute is no longer needed.

MyCustomerController

private readonly ICustomerService CustomerService;

ctor : MyCustomerController(ICustomerService CustomerService){ this.CustomerService= CustomerService;}  //injected

Then on a save:

public ActionResult Save(string id)
{
     …  CustomerService.SaveCustomer(Customer);
}

————-

As far as the IoC goes, I’m doing that all within the Global.cs

ie.

ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(Container));

_container.RegisterControllers(Assembly.Load(“Controllers”));

Then I use reflection to add the Dao’s and the Services’s to the container.  It uses Windsors ‘autowiring’ to handle creation based for dependencies.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s