Rebind NInject issue when dynamically changing connection string

In the connection string, I have to dynamically pass the loggeduserid value using the attribute name = userid application name in the connection string and logging into SQL Server using the select app_name () query.

Technologies used: 1) .net 4.0 2) NHibernate 3) Ninject

Before logging in, I use the Ninject IoC and NHibernate containers to load the connection string without the application name attribute and after logging in. I pass the registered user id as the constructor value and overwrite the NhibernateConfiguration class as follows

Before entering 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 logging in, loggeduserid with a constructor argument is as follows.

using (var kernal = ServiceLocator.GetKernel())
{
 kernal.Rebind<NHibernateConfiguration>().To<NHibernateConfiguration>()
.WithConstructorArgument("loggedUserId", user.Id);
}

NHibernateConfiguration.

, NHibernateConfiguration Ninject

+1
1

. . :

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
}

. factory.

Bind<ISession>().ToMethod(x => x.Kernel.Get<ISessionFactory>()
                .OpenSession());
+1

Source: https://habr.com/ru/post/1681485/


All Articles