How should one write an XPC service with state? - objective-c

I've read the NSXPC* docs, which advise making the vended service as stateless as possible. It's a good idea, at least to the docs and examples I've read, since the service and the calling app see each other as singletons and only one instance of the service runs at a time. This means that the methods are essentially non-member functions (to use a C++ term).
Why do I want to get around this? I want to put the network code into a XPC. Since the XPC will be working with a GUI app, which will have multiple windows, I need to support multiple simultaneous connections. That doesn't work with singletons, at least directly.
The network API is C-based, with the main state type a pointer to a custom struct. So why don't we do something similar:
Have the creation function return a value type, like NSUUID or something. (Passing a pointer across processes would be a bad idea.)
In the service, create a NSDictionary (or std::map or whatever) mapping between the NSUUID and the API C-pointer.
The various service APIs take the UUID and convert it to the C-pointer to use the network API.
Aside: Since the token is random, if the XPC service crashes, the main app will have a token that's useless after the XPC is restarted. Maybe I should a URL (which would have all the information to restart) instead. But then we get potential conflicts if two connections happen to be to the same server. Maybe I can combine the ideas with the token being a URL/UUID pair. (The UUID value would move from being returned by the service to supplied by the main app.)
Would this be a good way to implement state-full XPCs?

You may want to add a method to your service interface which replies with a long-lived proxy object. You can arrange for this to happen by means of a call to -[NSXPCInterface setInterface:forSelector:argumentIndex:ofReply:], passing YES for the last parameter. Details are available here:
https://developer.apple.com/library/mac/documentation/Foundation/Reference/NSXPCInterface_reference/#//apple_ref/occ/instm/NSXPCInterface/setInterface:forSelector:argumentIndex:ofReply:

Related

Unable to access the service instance from within an implementation of IDataContractSurrogate

this is my first post, and I really have tried hard to find an answer, but am drawing a blank thus far.
My implementation of IDataContractSurrogate creates surrogates for certain 'cached' objects which I maintain (this works fine). What doesn't work is that in order for this system to operate effectively, it needs to access the service instance for some properties of the instance which it is maintaining from the interaction with its client. Also, when my implementation of IDataContractSurrogate works in its 'client mode' it needs access to the properties of the client instance in a similar way. Access to the information from the client and service instance affects how I create my surrogate types (or rather SHOULD do if I can answer this question!)
My service instancing is PerSession and concurrent.
On the server side, calls to GetDataContractType and GetDeserializedObject contain a valid OperationContext.Current from which I can of course retreive the service instance. However on the client side, none of the calls yield an OperationContext.Current. We are still in an operation as I am translating the surrogate types to the data contract types after they have been sent from the server as part of its response to the client request so I would have expected one? Maybe the entire idea of using OperationContext.Current from outside of an Operation invocation is wrong?
So, moving on, and trying to fix this problem I have examined the clientRuntime/dispatchRuntime object which is available when applying my customer behaviour, however that doesn't appear to give me any form of access to the client instance, unless I have a message reference perhaps... and then calling InstanceProvider. However I don't have the message.
Another idea I had was to use IInstanceProvider myself and then maybe build up a dictionary of all the ones which are dished out... but that's no good because I don't appear to have access to any session related piece of information from within my implementation of IDataContractSurrogate to use as a dictionary key.
I had originally implemented my own serializer but thats not what I want. I'm happy with the built in serializer, and changing the objects to special surrogates is exactly what I need to do, with the added bonus that every child property comes in for inspection.
I have also looked at applying a service behavior, but that also does not appear to yield a service instance, and also does not let me set a Surrogate implementation property.
I simply do not know how to gain access to the current session/instance from within my implementation IDataContractSurrogate. Any help would be greatly appreciated.
Many thanks,
Sean
I have solved my problem. The short answer is that I implemented IClientMessageFormatter and IDispatchMessageFormatter to accomplish what I needed. Inside SerializeReply I could always access the ServiceInstance as OperationContext.Current is valid. It was more work as I had to implement my own serialization and deserialization, but works flawlessly. The only issue remaining would be that there is no way to get the client proxy which is processing the response, but so far that is not a show stopper for me.

Singleton with a delegate: Good idea or bad?

I have created objects that are interfaces to a web service. One typical object would be a "TaskService". When a client uses one of these objects, it invokes one of the service's methods (such as "GetTasks") and the service will asynchronously go off to call the remote web service, and post back the retrieved data via a delegate.
Currently, to use one of these services you have to create it with [[TaskService alloc] init], but I decided it makes more sense to make each service into a singleton object.
Is it common to see singleton objects that hold reference to delegates? My main issue with the design, is that each object, whenever it requires use of a particular service, will have to set itself as the delegate before invoking the service, which doesn't seem quite right to me... What if another object were to set itself as the delegate inbetween you setting yourself as the delegate and invoking the service?
Many thanks in advance!
Regards,
Nick
Imo this is not a good idea for the reason you cited. The Singleton pattern is really for things there are only one of, but it sounds like your app can have need for multiple instances of these services. I think you'd wind up working around this (using an operations queue or some kind of delegate multiplexer) when you really just need to instantiate multiple instances of your service.
When the occasion warrants the use of a Singleton object, I always avoid delegation for the reason you cite. Consumers of a singleton can't know (without some ugly coding) if they're stepping on some other consumer's toes by setting themselves as the one-and-only delegate of the singleton. NSNotifications are a much cleaner tool for the job; any arbitrary number of listeners can consume the notifications without caring who else may be listening.
Delegation works best when there is clear ownership between the classes. Nobody owns a singleton.
Singleton isn't really the problem, you cause the same sort of issues by simply instancing a class and passing it about as a global variable.
As other's have mentioned a queue is a possibility, or when you invoke a task on a service in your Singleton have it instance a TaskRequest object passing in the method and the call back delegate, that way requests can't trample on each other. In fact it would be a good idea to do that with a queue anyway.
The scope of a singleton is entire application. For example: Let consider the example of shopping application the logger data, about the user ID which need to be accessible on different part of application like order, payment, cart etc.
Delegates are used for 1 to 1 communication, for example: You can take as example You have two classes TV and remote control device. You want to change the channel of TV. Delegate methods of TV for changing channel are implemented in remote control device class. So you use remote control device and you change the channel of the TV.
The singleton is used to communicate with multiple receivers, while the delegation pattern is used usually for 1 to 1 communication.

Passing client context using Unity in WCF service application

I have a WCF service application (actually, it uses WCF Web API preview 5) that intercepts each request and extracts several header values passed from the client. The idea is that the 'interceptor' will extract these values and setup a ClientContext object that is then globally available within the application for the duration of the request. The server is stateless, so the context is per-call.
My problem is that the application uses IoC (Unity) for dependency injection so there is no use of singleton's, etc. Any class that needs to use the context receives it via DI.
So, how do I 'dynamically' create a new context object for each request and make sure that it is used by the container for the duration of that request? I also need to be sure that it is completely thread-safe in that each request is truly using the correct instance.
UPDATE
So I realize as I look into the suggestions below that part of my problem is encapsulation. The idea is that the interface used for the context (IClientContext) contains only read-only properties so that the rest of the application code doesn't have the ability to make changes. (And in a team development environment, if the code allows it, someone will inevitably do it.)
As a result, in my message handler that intercepts the request, I can get an instance of the type implementing the interface from the container but I can't make use of it. I still want to only expose a read-only interface to all other code but need a way to set the property values. Any ideas?
I'm considering implementing two interfaces, one that provides read-only access and one that allows me to initialize the instance. Or casting the resolved object to a type that allows me to set the values. Unfortunately, this isn't fool-proof either but unless someone has a better idea, it might be the best I can do.
Read Andrew Oakley's Blog on WCF specific lifetime managers. He creates a UnityOperationContextLifetimeManager:
we came up with the idea to build a Unity lifetime manager tied to
WCF's OperationContext. That way, our container objects would live
only for the lifetime of the request...
Configure your context class with that lifetime manager and then just resolve it. It should give you an "operation singleton".
Sounds like you need a Unity LifetimeManager. See this SO question or this MSDN article.

Things to consider while calling one WCF service from another

We are migrating set of WSE services to WCF platform.
The new WCF services are called over secured HTTP. (https)
I want to invoke an operation contract of one WCF service from another. Both the services are mostly hosted in the same IIS, but they can be on separate IIS server.
Do I need to take care of some things (which i obviously do not know at present) in this scenario?
Is there any special calling mechanism in this case?
Does calling mechanism change when call is synchronous and when it is asynchronous?
Can you suggest some type of binding which is readily available in this case?
1.) If the services are on the same box, use named pipes, unless you have any compelling reason not to, to communicate with each other. While WCF proper doesn't care about what you're doing as long as the address, binding and contract all match up (see what I did there?), .NET will when it comes to making network connections. The fewer you use, the better. (see http://msdn.microsoft.com/en-us/library/fb6y0fyc.aspx for more details)
2.) As stated in #1, if they're talking on the same box, use named pipes unless there's a good reason not to.
3.) Can you provide a little more detail on what you mean by this or what you're planning on doing? A lot of this is built out for you, so assuming you're familiar with implementing async methods and using async callbacks, the short answer is yes, it's different than calling an operation synchronously, but that's to be expected. Or do you mean IsOneWay = true? If that's the case, the calling mechanism is the same but there can be a number of other gotchas (e.g. faults)
4.) Named Pipes on the same box, BasicHttp otherwise (unless you need any of the additional features from WS).
but they can be on separate IIS server
In this case, you either can't use Windows authentication (if you were using it) or you have to set up some special delegates stuff on the domain to make it work. Windows Authentication won't "hop" between different servers. Here's some info on that, there's a lot of reading out there on the subject.
If they stay on the same server or you're not using Windows authentication, then it shouldn't be a problem.
Does calling mechanism change when call is synchronous and when it is
asynchronous?
Shouldn't matter, it's all the same on the service end. I will say that if the client calls X and X calls Y, X might as well call Y synchronously because it can't return to the client until Y is done anyway. (If X calls Y and Z, then X making async calls may make more sense.)
Can you suggest some type of binding which is readily available in
this case?
If you were using WSE before, then BasicHttpBinding is going to be the one closest to what you were doing and will look pretty familiar in what it outputs. It's also the simplest one to work with.
There shouldn't be anything special needed just because a WCF service method calls another WCF service. A WCF service doesn't "care" what other application types are calling its methods so long as they use the correct service contract, data contract, endpoint, and binding settings.
Just make sure that both service methods return promptly, and don't cause execution to block for long periods of time.

Sharing session between WCF services

I have been working on splitting up the app tier and web tier of a web application. In the app tier, I managed to separate the business logic into a bunch of services exposed using WCF proxies. The problem is that these services talk to another legacy application that uses a large CLR object as its primary means of communication. To keep things quick, I had been keeping a copy of this object in the session after I created it the first time. Now I know that WCF can do sessions, but the session storage is per service whereas my business logic is now split into multiple services (as it should be).
Now the questions:
Is there a way to share session storage between WCF services hosted on the same host?
Is this even something I should be doing?
If not, then what are the best practices here?
This is probably not the first time somebody’s had a large business object on the server. Unfortunately for me, I really do need to cache this object per user (hence the session).
It’s possible the answer is obvious and I'm just not seeing it. Help please!
I think instance context sharing can help
http://msdn.microsoft.com/en-us/library/aa354514.aspx
As far as I understand WCF, it is designed to be as stateless as it could be. In a session you can remember some values in your service, but objects are not meant to live outside the scope of a session.
Therefore, I'd think you are in trouble.
Of course, there might be some way to store and exchange objects between sessions that I don't know (I use WCF, but I don't know very much about it, apart from what I need for myself).
(if there is a way to share objects between services, it probably would only work on services you host yourself. IIS hosting might recycle your service sometimes)
Perhaps you can wrap this object in a singleton service. This is a service with only one instance, which will not be destroyed between calls. Because you need an object for each user, this service has to manage a list of them and the calling services has to provide the needed authentication data (or sessionid). Don't forget a timeout to get rid of unneeded objects...
Create a facade service which hosts the large CLR object on behalf of the other app tier services. It can work as an adapter, allowing more specific session identifiers to the more advanced app tier services you have created. The facade can provide a session identifier, like a GUID, which your app tier services can use to get re-connected with the large CLR object.
This provides a few advantages:
Some of your app tier might not need to know about the CLR object at all. They only communicate with the remote facade.
the 'large CLR object' host retains the session object on behalf of the other services who can now share it.
The app tiers now have a facade through which they talk to the legacy service. As you work to refactor this legacy service, the app tier doesn't have to change.
Depending on your setup, you may be able to host the facade via in proc hosting which will give retain performance boost you are seeking.
Breaking things up into subservices seems like a good idea if you want to be able to spread the app out over a farm. However, it's important to keep in mind that whenever an object crosses the appdomain boundary at the vary least it will have to be copied in memory.
It all depends on how big the object is and what kind of data it holds.
If you don't want to pass the object because it's too large you may want to make a query API for the service which receives it. In this way you could manipulate that object without having to do expensive serialization or remoting.
Keep it simple. Since you already have access to Session in your WCF, you can use the SessionID from there. Now:
Create a static dictionary somewhere, where the Key is your sessionId and the value is the business object you want to store.
Instead of accessing the business object in session, just access the sessionid and get the business object from the Value of your dictionary.
(You can also use some type of caching if you wish, for example System.Web.Caching, that way you don't have to cleanup the dictionary manually)