简体   繁体   中英

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.

At the moment, the connection string is supplied, as standard within the web.config and this all works successfully.

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.

In order to compensate for this I have overidden the CreateDbContext() method within my DbDomainService implementation as follows:

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.

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.

Am I doing something wrong? Or is it not possible to have the DbDomainService change it's connection dynamically?

I'm thinking of the instancing model of your domainservice class. Have you tried a custom 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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