Create a Unit Of Work and Repository for each entity using NHibernate or EntityFramework

The IFooUnitWork interface, you can use it to switch between EntityFramework and NHibernate:
public class FooUnitOfWork : UnitOfWork
{
	public FooUnitOfWork(IDataSession dataSession)
		: base(dataSession)
	{
	}

	IReadOnlyRepository<Customer> CustomerRepository { get { return new ReadOnlyRepository<Customer>(DataSession); } }

	IRepository<Order> OrderRepository { get { return new Repository<Order>(DataSession); } }
}

Create the NHibernate UnitOfWork using ConfOrm:
var connection =
	new NhibernateMicrosoftSqlServerConnection
		{
			Catalog = Connection.Catalog, 
			DataSource = Connection.DataSource, 
			IsTrustedConnection = Connection.IsTrustedConnection
		};

var configuration =
	new NhibernateConfigurationBuilder()
		.ProxyFactory<NHibernate.ByteCode.Castle.ProxyFactoryFactory>()
		.Build(connection, new FooNhibernateMapping().GetMapping());

var sessionFactory = configuration.BuildSessionFactory();

using (FooUnitOfWork fooUnitOfWork = new FooUnitOfWork(new NhibernateDataSession(sessionFactory.OpenSession())))
{
    fooUnitOfWork.CustomerRepository.Add(new Customer { Id = Guid.NewGuid(), FirstName = "Bill" });
    fooUnitOfWork.Commit();
}


Create the EntityFramework UnitOfWork using code-first and DbContext
var connection =
	new EntityFrameworkMicrosoftSqlServerConnection
		{
			Catalog = Connection.Catalog,
			DataSource = Connection.DataSource,
			IsTrustedConnection = Connection.IsTrustedConnection
		};

var configuration =
	new EntityFrameworkConfigurationBuilder();

var sessionFactory = configuration.Build(new FooDbModelBuilder(), connection);

using (FooUnitOfWork fooUnitOfWork = new FooUnitOfWork(new EntityFrameworkDataSession(sessionFactory.OpenSession())))
{
    fooUnitOfWork.CustomerRepository.Add(new Customer { Id = Guid.NewGuid(), FirstName = "Bill" });
    fooUnitOfWork.Commit();
}

Last edited Jun 10, 2011 at 6:36 AM by teoarch, version 10

Comments

No comments yet.