Reputation: 5651
I wonder if anyone can help. I'm writing an MVC3 app that needs to connect to 2 separate databases. I'm using NHibernate and Ninject for the persistence. All is going well connecting to one db. In my Global.asax.cs file I have:
public class MvcApplication : NinjectHttpApplication
{
public static ISessionFactory SessionFactory = CreateSessionFactory();
public MvcApplication()
{
this.BeginRequest += new EventHandler(MvcApplication_BeginRequest);
this.EndRequest += new EventHandler(MvcApplication_EndRequest);
}
void MvcApplication_EndRequest(object sender, EventArgs e)
{
CurrentSessionContext.Unbind(SessionFactory).Dispose();
}
void MvcApplication_BeginRequest(object sender, EventArgs e)
{
CurrentSessionContext.Bind(SessionFactory.OpenSession());
}
private static ISessionFactory CreateSessionFactory()
{
var cfg = new Configuration().Configure(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "nhibernate.config"));
return cfg.BuildSessionFactory();
}
...
protected override IKernel CreateKernel()
{
var kernel = new StandardKernel();
kernel.Load(Assembly.GetExecutingAssembly());
return kernel;
}
protected override void OnApplicationStarted()
{
log4net.Config.XmlConfigurator.Configure();
HibernatingRhinos.Profiler.Appender.NHibernate.NHibernateProfiler.Initialize();
base.OnApplicationStarted();
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
}
And I have a Ninject class
public class AdultDirectionsNinjectModule : NinjectModule
{
public override void Load()
{
...
this.Bind<ISession>().ToMethod(x => MvcApplication.SessionFactory.GetCurrentSession());
...
Having read around and being a .NET newbie, what I find difficult is to work out how to connect my application to multiple databases. I've searched the web but lots of the examples are either way over my head or not quite for the issue I have. I realise that I need multiple session factories, but then I'm not sure how to wire this up with Ninject. Ninject will only allow me to bind one ISession which is a problem if I need multiple Session Factories. I'm using the xml configuration for NHibernate and not fluent.
Could someone provide some easy to follow help to getting two session factories up and running. Any help will be gratefully received.
Upvotes: 1
Views: 690
Reputation: 61795
You'd use contextual binding and/or .Named()
. Fortunately the relevant docs have yet to be updated to Ninject V2 syntax (but watch this space on the wiki...) have lots of examples of different mechanisms now.
Upvotes: 1