I have a factory that returns the UOW
class UnitOfWorkFactory : IUnitOfWorkFactory
{
private UnitOfWork.Factory factory;
public ISession Session;
public IRepository Repository { get; set; }
public UnitOfWorkFactory(UnitOfWork.Factory factory,
ISession session, IRepository repository)
{
this.factory = factory;
this.Session = session;
Repository = repository;
}
public IUnitOfWork Create()
{
return factory(Session, Repository);
}
}
The first call to the factory returns a new instance of the UOW. However, on subsequent calls, it returns previously created instances, not the new. I used the instructions developers "autofac" to use a delegate factory
public class UnitOfWork : IUnitOfWork
{
public ISession Session;
public IRepository Repository { get; set; }
private Transaction transaction;
public UnitOfWork(ISession session, IRepository repository)
{
this.Session = session;
Repository = repository;
transaction = Session.Transaction;
}
public delegate IUnitOfWork Factory(ISession transaction,
IRepository repository);
public void Dispose()
{
if (transaction.IsActive)
{
//Rollback
}
Session.Dispose();
}
public void Commit()
{
transaction.Commit();
}
}
Registration into IoC
builder.RegisterType<Repository>().As<IRepository>().InstancePerDependency();
builder.RegisterType<UnitOfWork>().As<IUnitOfWork>().InstancePerLifetimeScope();
builder.RegisterType<UnitOfWorkFactory>().As<IUnitOfWorkFactory>().InstancePerLifetimeScope();
Your class UnitOfWork is registered as "Instance per liferime scope". Since you don't create a separate lifetime scope, current lifetime scope will be used every time you create a IUnitOfWork, and the IUnitOfWork will be created only once.
Change the registration: