简体   繁体   English

Silverlight WCF RIA服务动态更改连接字符串

[英]Silverlight WCF RIA Services Dynamically Change Connection String

We have a Silverlight application which uses WCF RIA Services and Entity Framework 4.1 to connect to a database. 我们有一个Silverlight应用程序,它使用WCF RIA服务和Entity Framework 4.1连接到数据库。

At the moment, the connection string is supplied, as standard within the web.config and this all works successfully. 目前,已提供连接字符串,这是web.config中的标准配置,并且都可以成功运行。

However, I now want to be able to change the connection string dynamically at runtime based on amongst other things, the user logged in. 但是,我现在希望能够在运行时基于用户登录等动态地更改连接字符串。

I've found some other posts which hint at doing this, but they are using ObjectContext whereas we are using DbContext within the System.Data.Entity namespace and also the DbDomainService class. 我发现了其他一些暗示可以做到这一点的帖子 ,但是它们使用的是ObjectContext,而我们在System.Data.Entity命名空间以及DbDomainService类中使用的是DbContext。

In order to compensate for this I have overidden the CreateDbContext() method within my DbDomainService implementation as follows: 为了弥补这一点,我在DbDomainService实现中重写了CreateDbContext()方法,如下所示:

protected override CoreContext CreateDbContext()
{
    dbServer = null, dbName = null;

    httpCookie = System.Web.HttpContext.Current.Request.Cookies["DBServer"];
    if (httpCookie != null)
    {
        dbServer = httpCookie.Value;
    }

    var cookie = System.Web.HttpContext.Current.Request.Cookies["DBName"];
    if (cookie != null)
    {
        dbName = cookie.Value;
    }

    if (dbServer == null && dbName == null)
    {
        return new CoreContext();
    }

    string connStr = "Data Source=" + dbServer + ";Initial Catalog=" + dbName + ";Integrated Security=true";
    return new CoreContext(connStr);
}

This works successfully the first time the Silverlight application is loaded, however, on all subsequent loads, the same connection as established initially is used despite changing the values being substituted into the connection string. 首次加载Silverlight应用程序时,此操作成功完成,但是,在所有后续加载中,尽管更改了替换为连接字符串的值,但仍使用与最初建立的连接相同的连接。

The only way to get the connection to be changed seems to be to recycle the application pool in IIS and load the app again. 更改连接的唯一方法似乎是回收IIS中的应用程序池并再次加载该应用程序。

Am I doing something wrong? 难道我做错了什么? Or is it not possible to have the DbDomainService change it's connection dynamically? 还是无法让DbDomainService动态更改其连接?

I'm thinking of the instancing model of your domainservice class. 我在考虑您的domainservice类的实例化模型。 Have you tried a custom IDomainServiceFctory ? 您是否尝试过自定义IDomainServiceFctory It permits you to decide when to create a new instance of them and is really simple to implement. 它使您可以决定何时创建它们的新实例,并且实现起来非常简单。
Take also a look at this post by Fredrik Normén. 也看看这个帖子由Fredrik诺门。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM