简体   繁体   中英

Multiple WCF service contracts to share same session

I have two service contracts and they get implemented as one. Naturally, I'm creating two client proxies for those contracts. Is it possible to maintain session between these two proxies. (btw I'm just starting with WCF so cut me some slack if I'm being too dumb)

As an example,

[ServiceContract(SessionMode = SessionMode.Required)]
public interface IFoo
{
[OperationContract]
void DoFoo(int something);
}

[ServiceContract(SessionMode = SessionMode.Required)]
public interface IBoo
{
[OperationContract]
int DoBoo();
}

[ServiceBehavior(InstanceContextMode =InstanceContextMode.PerSession)]
public class myservice: IFoo, IBoo
{
int somevalue;
void DoFoo(int something)
{
somevalue = something;
}
int DoBoo()
{
return somevalue;
}
}

Client Side Code: using ServiceReference1;

static void main()
{
DoFooServiceClient fooproxy = new DoFooServiceClient();
DoBooServiceClient booproxy = new DoBooServiceClient();
fooproxy.DoFoo(5);
Console.WriteLine(booproxy.DoBoo());
}

I want it to return 5 but it returns 0. I know what's wrong, it is indeed creating two instances but is it possible to force them to use same instance? If I used static wouldn't it be the same value for all clients?

Since WCF instancing operates at the service contract level, you are going to struggle to share memory between only these two services.

Yes you could use a some static type but, as you say, the value would be synchronized across all service instances regardless, which is not the behavior you require.

An option would be to use some persistent resource like a database, or a singleton service instance, to store this shared data.

Another option may be possible, if you were to define Doo and Foo as singleton services for instancing. This would mean that you could access the state of each service directly from the service host, but would require some mediation logic to synchronize values between them.

I will try the mediation logic to sync values but that would require additional client side code, wouldn't it?

It does not require client side code, but something on the service host to sync values between two service instances. I can only think of a way to do this if the services are both singleton instances. This becomes more complicated if you are using IIS for hosting, as this means you are not exposed to the actual ServiceHost instances.

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