views:

39

answers:

1

I am designing my first Layered Application which consists of a Data, Business, and a Presentation layer.

My business components (e.g, Business.Components.UserComponent) currently has the following method:

public void Create(User entity)
{
    using (DataContext ctx = new DataContext())
    {
        ctx.Users.AddObject(entity);
        ctx.SaveChanges();
    }
}

I like this design. However, I've encountered some examples online that would recommend the following implementation:

public void Create(User entity)
{
    // Instanciate the User Data Access Component
    UserDAC dac = new UserDAC();
    dac.InsertUser(entity);
}

This would result in creating a Data Access Component for all Entities, each containing the basic methods (Create, Edit, Delete...etc).

This seems like double work since I would have to create the Data Access Components with the basic methods as well as the Business Components that just simply calls the methods in the Data Access Component.

What would be considered best practice for properly implementing the basic CRUD functionalities in a Layered Application? Should they be 'coded' in the Business Component or in a Data Access Component?

+1  A: 

It depends. If you expect that your business layer simply do CRUD operations than you can follow your initial approach. If you plan to use some big business logic where business component will work with many entities second approach is better.

Reason why people like to use second approach is testing and persistance ignorance. If you use first approach your business component is tightly coupled with Entity framework. Mocking ObjectContext is not very easy task so testing is hard. If you use second approach your business layer is independent on persistance layer. You can easily test it and you can even change persistance layer if you need to. But those are more advanced concepts which you are probably not looking for at the moment. Your code would need some additional improvement to be testable.

DAC can be also implemented as Repository. There are plenty of ways how to create generic repository so that you have only one class and you define the entity type when instancing repository:

var repository = new GenericRepository<User>();

Also be aware that using separate data access layer introduces new complexity because sometimes it is reasonable to share single context among multiple repositories. This comes together with something known as Unit of work pattern.

There are plenty of articles about implementing Repository and Unit of work patterns on the Internet. I have some of them stored as favorites at home so If you are interested I can include them to my answer later on.

Ladislav Mrnka
Thanks Ladislav, your post was helpful. If you could include some examples on Repository and Unit of Work Pattern that would be nice.
gottalovedotnet