开发者

Change DataSource WCF Data Services

Anybody know how to change the current data source of a DataServices on the fly?

Example I want to consult t开发者_StackOverflow中文版he service and pass a parameter saying to pick up another connection, Is Possible?


It should be really simple there is a override method you can use that creates a data source.

//
// Summary:
//     Creates a data source of the template class that will be used by the data
//     service.
//
// Returns:
//     An instance of the data source.
protected virtual T CreateDataSource();

When overridden it should look like this.

protected override MyModel CreateDataSource()
{
    MyModel modal = new MyModal();

    return modal;
}

That would give the ability to create a data source with a different connection string.

Below I have added a list of things you can do to pass this information to DataService so you can change the connection of your data source on the fly.

1. Request Headers

You can on the client side pass extra information to data services if you subscribe the SendingRequest on the DataServiceContext, which allows you to add extra request headers to your web requests. Once you do that for example you can read them by accessing the System.Web.HttpContext.Current.Request.Headers on the CreateDataSource method.

It would have been nice to be able to get access to the internal IDataService interface which exposes all the information you need to do this sort of thing.

2. Query String

Another way with out doing the SendingRequest and the headers is to add a QueryString parameter that you can check for in the specific value and initialize the data source accordingly.

3. Identity

You can use the users credentials to chose what data source you want to use.

Again these are just ideas about how to achieve this selection of data sources.

You can do a number of things with the strategies above I Hope this answer your question and it helps you with your problem

PS.: as long as what you mean by "change the data source" is change the connection string of your model to another database the above will work.


If you want to pass the desired connection in the URL I would think your only option is to create two DataServiceHosts.

http://server/datasource1/service.svc

and

http://server/datasource2/service.svc


Try overriding the CreateDataSource function in the DataService class.

This will allow you to create your own DataSource with any connection string.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜