Reputation: 107
I've implemented repository & unit of work patterns for nhibernate. I use ninject as DI. I have more than one databases so I have different implementations of unit of work with different repos. I use to inject IDatabaseConnection interface to unit of work:
public interface IDatabaseConnection
{
ISessionFactory SessionFactory { get; }
}
and unit of work:
public class SomeUnitOfWork : GenericUnitOfWork
{
[Inject]
public SomeUnitOfWork(IDatabaseConnection connection)
: base(connection)
{
}
and some repos
[Inject]
public IRepository<Transaction> Transactions { get; private set; }
[Inject]
public IRepository<Paramdef> Paramdefs { get; private set; }
[Inject]
public IRepository<Transmap> Transmaps { get; private set; }
[Inject]
public IRepository<User> Users { get; private set; }
GenericRepository implementation that I use when binding IRepository at ninject module has argument that awaits for ISession than can be retrivered from ISessionFactory. How can I do it?
Upvotes: 0
Views: 94
Reputation: 507
You must inject ISession into your UoW instead of the factory, that it can be created by Ninject. The session should be in some scope e.g. InRequestScope for web applications. Then add some condition to the session binding that defines which one to use. E.g.
Bind<ISession>().ToMethod(context => context.Kernel.Get<ISessionFactory>("DB1")).WhenAnyAnchestorNamed("UoW1").InRequestScope();
Bind<SomeUnitOfWork>().ToSelf().Named("UoW1");
Upvotes: 1