问题
In connection string i should dynamically passing the loggeduserid value by using the attribute application name=userid in connection string and getting into SQL Server by using the query select app_name().
Technologies used: 1).net 4.0 2)NHibernate 3)Ninject
Before logged-in i am using Ninject IoC container and NHibernate to load the connection string without the application name attribute and after logged in I am passing the logged user id as a constructor value and rebinding the NhibernateConfiguration class is as follows
Before Logged in inject the NHibernateConfiguration
public override void Load()
{
Bind<ISession>().ToMethod(x => x.Kernel.Get<NHibernateConfiguration>()
.GetSessionFactory()
.OpenSession());
Bind<ISessionFactory>().ToMethod(x => x.Kernel.Get<NHibernateConfiguration>().GetSessionFactory());
}
After logged in passing the loggeduserid with the constructor argument is as follows.
using (var kernal = ServiceLocator.GetKernel())
{
kernal.Rebind<NHibernateConfiguration>().To<NHibernateConfiguration>()
.WithConstructorArgument("loggedUserId", user.Id);
}
but I am not able rebind or inject the NHibernateConfiguration class .
Please help me how to rebind the NHibernateConfiguration class by using Ninject
回答1:
Don't use rebind during the execution of your application. This can cause many problems. Use conditional bidnings instead:
kernel.Bind<NHibernateConfiguration>().To<NHibernateConfiguration>();
kernel.Bind<NHibernateConfiguration>().To<NHibernateConfiguration>()
.When(ctx => IsLoggedIn())
.WithConstructorArgument("loggedUserId", request => user.Id);
private bool IsLoggedIn()
{
// add code to decide if the user is logged in
}
Also your session binding doesn't make much sense. It should get the session factory instead.
Bind<ISession>().ToMethod(x => x.Kernel.Get<ISessionFactory>()
.OpenSession());
来源:https://stackoverflow.com/questions/9209687/issue-rebind-ninject-while-dynamically-change-the-connection-string