Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you implement a 3 layer model with NHibernate?

Taking the traditional 3 layer approach (not necessarily 3 tiers):

UI BLL DAL

How does NHibernate fit? In most cases I see people allowing NHibernate to directly populate domain objects/entities, which obviously requires a reference from NHibernate to these entities. If domain entities are part of the BLL, this seems to require a reference from the DAL (where NHibernate resides) to the BLL (where domain objects reside).

Doesn't this go against the typical thinking of separating each layer, with each layer only being dependent on the one below it? What am I missing here?

like image 766
Casey Wilkins Avatar asked Jan 31 '11 20:01

Casey Wilkins


2 Answers

I can give you an example, how I generally layer with NHibernate for a n-tier architecture:

Data Access Layer

  • NHibernate SessionFactory
  • Mappings with FluentNHibernate

Example for a mapping:

public class CategoryMap : ClassMap<Domain.Entities.Category>
{
    public CategoryMap()
    {
        ...
    }
}

Business Layer

  • Repositories : BaseRepository

Example for a repository:

public class CategoryRepository : BaseRepository<Domain.Entities.Category>,
    Domain.DataInterfaces.Business.Repositories.ICategoryRepository
{
    public CategoryRepository(ISession session)
        : base(session)
    {
    }
}
  • BaseRepository (CRUD, GetById, GetAll)

Example for a base repository:

public class BaseRepository<T> : IBaseRepository<T>
{
    public ISession Session { get; set; }

    public BaseRepository(ISession session)
    {
        Session = session;
    }
 }

Domain Layer

  • DataInterfaces (IRepository, IBaseRepository)
  • Entities : BaseEntity
  • Persistance (IEntity, IBaseEnity)

So, the only layer which is referencing NHibernate is actually the data layer and the business (NHibernate.ISession). The domain layer is shared between all layers and does not know about NHibernate. For simplicy you could merge the business and data layer into one layer. I generally tend to seperate them, but it depends on the project size.

enter image description here

If you really want seperation, I also suggest you to have a look at dependency injection to reduce the dependencies between different layers.

Hope that helps you.

like image 90
Martin Buberl Avatar answered Nov 18 '22 11:11

Martin Buberl


NHibernate is most suitable for a different architecture (still layered, but not stacked the same way).

The presentation layer uses NHibernate as a Data Mapper (and Unit of Work) to decouple its Domain Model (that is, its business logic) from persistence concerns.

like image 4
Jeff Sternal Avatar answered Nov 18 '22 12:11

Jeff Sternal