【问题标题】:Can one configure a single session factory using both cfg.xml and programming?可以同时使用 cfg.xml 和编程来配置单个会话工厂吗?
【发布时间】:2014-03-05 04:42:09
【问题描述】:

有人知道如何动态配置连接字符串,同时将其他参数保留在 cfg.xml 文件中吗?

遵循 cfg.xml 文件中应包含的内容:

  • 方言
  • 连接驱动程序
  • 查询替换

以及需要以编程方式配置的内容:

  • 连接字符串(使用每个用户和每个实例)

这意味着连接字符串是动态构建的,其他参数在 cfg.xml 文件中应该是静态的(直到它们在 XML 中手动更改)。

我想知道这是否可以解决问题?

NHibernate using single configuration file to connect to multiple dbs

顺序

  • 应用程序已启动
  • 应用程序提示用户输入他的凭据和数据库实例
  • 应用程序根据数据库验证身份验证,并根据数据库响应授予或拒绝访问权限。

【问题讨论】:

    标签: xml nhibernate configuration configuration-files


    【解决方案1】:

    我们可以将两者结合起来。有一个示例,首先读取配置,然后根据需要使用尽可能多的设置对其进行扩展:

    ISessionFactory CreateSessionFactory(string connectionString) // from outer source
    {
        // the Configuration, i.e.: native, NHibernate one
        var configuration = new NHibernate.Cfg.Configuration();
    
        var configFile = ... // a path to configuration ;
    
        // read that configuration file    
        var document = XDocument.Load(configFile);
    
        // pass it to the Configuration 
        using (var reader = document.CreateReader())
        {
            configuration.Configure(reader);
        }
    
        // so, the config file is applied, 
        // no its our dynamic turn
        configuration.SetProperty("connection.connection_string", connectionString);
        configuration.SetProperty(....);
    
        // and now, we can ask for configuration to produce the factory
        var factory = configuration.BuildSessionFactory();
    
        return factory;
    }
    

    【讨论】:

    • +1 我终于做到了。感谢您的回答,我希望这可以帮助其他人。
    • 太好了,很高兴看到这一点。 NHibernate 是一个了不起的工具 ;)
    猜你喜欢
    • 2011-12-16
    • 2013-12-30
    • 2022-09-23
    • 2017-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多