如何在服务堆栈中动态更改SQL Server连接字符串 [英] How to change sql server connection string dynamically in service stack

查看:123
本文介绍了如何在服务堆栈中动态更改SQL Server连接字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究Asp.Net MVC和ServiceStack.我正在尝试使用servicestack ormlite连接到sql server数据库.像

I am working on Asp.Net MVC and ServiceStack. I am trying to connect to the sql server database using servicestack ormlite. like

 var connectionString = ConfigurationManager.ConnectionStrings["AppDb"].ConnectionString;
 container.Register<IDbConnectionFactory>(
 new OrmLiteConnectionFactory(connectionString,
                    SqlServerOrmLiteDialectProvider.Instance)
                {
                    ConnectionFilter = x => new ProfiledDbConnection(x, Profiler.Current)
                });

我能够连接到数据库,但是在我的场景中,我需要动态更改连接字符串.这意味着我需要从Request主体读取内容并准备一个连接字符串.在servicestack中,我们在AppHost类中配置sql server连接字符串,这意味着在应用程序启动时.但是我需要在控制器中设置连接字符串. 我尝试过将其放在会话中,并在ClassLibrary SeviceBase类中使用该会话.但是我无法在类库中使用asp.Net会话.如何在服务堆栈中动态更改sql server连接字符串.所以请引导我.

I am able to connect to database, But in my scenario i need to change the connection string dynamically.. That means i need to read the content from Request body and prepare a connection string. In servicestack we configure sql server connection string in AppHost class that means at app start. But i need to set the connection string in my controller. I have tried like place it in session and use that session in ClassLibrary SeviceBase class. But I am unable to use asp.Net sessions in class libraries.How to change sql server connection string dynamically in service stack. so please guide me.

推荐答案

我将在请求范围内更改要重用的IDbConnectionFactory,而不是在所有请求中共享的默认默认值. 我还创建了一个静态方法(GetDatabaseConnectionFactory()),该方法使用自定义连接字符串将OrmLiteConnectionFactory的实例返回到IoC容器.

I would change the IDbConnectionFactory to be reused in the scope of the request, instead of the current default, which shares it among all requests. I have also created a static method (GetDatabaseConnectionFactory()) which returns the instance of OrmLiteConnectionFactory to the IoC container with the custom connection string.

为了确定连接字符串,我使用了一个请求过滤器,该过滤器仅读取参数connectionstring.如果未设置,将使用默认值.然后,此值是 设置在集合中,可以通过GetDatabaseConnectionFactory()方法进行访问.

To determine the connection string, I have used a request filter, which simply reads the parameter connectionstring. If it is not set it will use a default value. This value is then set in the RequestContext.Items collection, which can be accessed by the GetDatabaseConnectionFactory() method.

切记以这种方式公开连接字符串很危险,请始终彻底检查任何连接字符串值,以确保它们不包含恶意值. 即确保他们不要尝试连接到管理数据库或其他服务器,也不要更改默认设置替代等.

Remember exposing connection strings this way is dangerous, always check any connection string values thoroughly to ensure they don't contain malicious values. i.e. Ensure they don't try to connect to administrative databases, or a different server, or change default setting overrides etc.

在您的AppHost中:

In your AppHost:

public override void Configure(Container container)
{
    container.Register<IDbConnectionFactory>(c => GetDatabaseConnectionFactory()).ReusedWithin(ReuseScope.Request);

    RequestFilters.Add((req,res,obj) => {
        // Default value
        var defaultConnectionString = ConfigurationManager.ConnectionStrings["AppDb"].ConnectionString;

        // Get the connection string from the connectionstring parameter, or use default
        var dbConnectionString = req.GetParam("connectionstring") ?? defaultConnectionString;

        // You should perform some checks here to make sure the connectionstring isn't something it shouldn't be
        // ...

        // Save the connection string to the HostContext.Instance.Items collection, so we can read it later
        HostContext.Instance.Items.Add("ConnectionString", dbConnectionString);
    });
}

public static IDbConnectionFactory GetDatabaseConnectionFactory()
{
    // Read the connection string from our HostContext Items
    var dbConnectionString = HostContext.Instance.Items["ConnectionString"];

    if(dbConnectionString == null)
        throw new Exception("Connection string has not been set");

    // Return the connection factory for the given connection string
    return new OrmLiteConnectionFactory(dbConnectionString, SqlServerOrmLiteDialectProvider.Instance) {
        ConnectionFilter = x => new ProfiledDbConnection(x, Profiler.Current)
    });
}

用途:

using System;
using Funq;
using ServiceStack.ServiceInterface;
using ServiceStack.ServiceHost;
using ServiceStack.WebHost.Endpoints;
using ServiceStack.OrmLite;
using ServiceStack.Common;

ServiceStack V4:

public override void Configure(Container container)
{
    container.Register<IDbConnectionFactory>(c => GetDatabaseConnectionFactory()).ReusedWithin(ReuseScope.Request);

    GlobalRequestFilters.Add((req,res,obj) => {
        // Default value
        var defaultConnectionString = ConfigurationManager.ConnectionStrings["AppDb"].ConnectionString;

        // Get the connection string from the connectionstring parameter, or use default
        var dbConnectionString = req.GetParam("connectionstring") ?? defaultConnectionString;

        // You should perform some checks here to make sure the connectionstring isn't something it shouldn't be
        // ...

        // Save the connection string to the RequestContext.Items collection, so we can read it later
        HostContext.RequestContext.Items.Add("ConnectionString", dbConnectionString);
    });
}

public static IDbConnectionFactory GetDatabaseConnectionFactory()
{
    // Read the connection string from our Items
    var dbConnectionString = HostContext.RequestContext.Items["ConnectionString"];

    if(dbConnectionString == null)
        throw new Exception("Connection string has not been set");

    // Return the connection factory for the given connection string
    return new OrmLiteConnectionFactory(dbConnectionString, SqlServerOrmLiteDialectProvider.Instance) {
        ConnectionFilter = x => new ProfiledDbConnection(x, Profiler.Current)
    });
}

用途:

using System;
using Funq;
using ServiceStack;
using ServiceStack.Data;
using ServiceStack.OrmLite;
using ServiceStack.OrmLite.Sqlite;

这篇关于如何在服务堆栈中动态更改SQL Server连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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