Issue Rebind NInject while dynamically change the connection string

故事扮演 提交于 2019-12-11 04:43:35

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!