发出重新绑定NInject而动态地更改连接字符串 [英] Issue Rebind NInject while dynamically change the connection string

查看:308
本文介绍了发出重新绑定NInject而动态地更改连接字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在连接字符串我应该动态地通过使用连接字符串属性的应用程序的名称=用户标识和获取到SQL Server使用查询选择APP_NAME()传递loggeduserid值。

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().

用到的技术: 1).NET 4.0 2)NHibernate的 3)Ninject

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

在登录的我使用Ninject IoC容器和NHibernate加载连接字符串,而不应用程序的名称属性,并记录在我传递的登录用户ID为构造函数值,并重新绑定后NhibernateConfiguration类如下:

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

在登录中注入NHibernateConfiguration

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());

        }

登录传递loggeduserid与构造函数参数后如下:

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);
}

但我不能重新绑定或注入NHibernateConfiguration类。

but I am not able rebind or inject the NHibernateConfiguration class .

请帮我如何使用Ninject重新绑定NHibernateConfiguration类

Please help me how to rebind the NHibernateConfiguration class by using Ninject

推荐答案

不要使用你的应用程序的执行过程中重新绑定。这可能会导致很多问题。使用条件bidnings来代替:

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());

这篇关于发出重新绑定NInject而动态地更改连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆