tags:

views:

150

answers:

3

I'll take TransactionScope as my example for now. Imagine every method in your WCF carries out database activity, and you want every call to be in a transaction. You could include a using block in every one of your methods, and that would work fine.

I'm wondering if there is an easier way to do this at a service, rather than method-level? For example Before/After method invocation events, or something in ServiceBehavior.

Now I know specifically for TransactionScope you can use the TransactionScopeRequired attribute, but if it didn't exist, what would you do?

A: 

Well, on the client, you don't necessarily always want to wrap just a single call into a TransactionScope or some other wrapper - maybe at some point, you'll want to have two, three or more calls grouped into a "scope".

You can extend WCF quite a bit on both client and server side - but this seems to me to be something that's so dependant on your actual application and almost on each time you make such a call that trying to force anything here would be not really beneficial.

Furthermore, the WCF extensibility really starts when the call has been made - so you can handle all sorts of scenarios, but you can't really wrap the outside code into some scope of any kind, I'm afraid.

Long story short: I don't think what you're trying to do makes a lot of sense, and I don't think you could even do it with just WCF - you'd almost have to extend the C# language (add compiler trickery to do something before and something else after each method call).

Marc

marc_s
+1  A: 

After further investigation, as marc says there appears to be no pure WCF solution.

However there is a solution that may be acceptable in certain cases.

<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />

If your application can run in ASP.NET compatibility mode, this means your WCF Service can include a HTTP Module. This can hook into the BeginRequest event, create the object and store it in HttpContext.Current.Items. On the EndRequest event we can then retrieve this object, and call its Dispose() method.

MattH
This unfortunately doesn't work if the operation is a one way operation.
Nigel Sampson
+2  A: 

This kind of thing could also be handled by Aspect Oriented Programming. This allows you to write code that can be "hooked" into any/every method of your class.

PostSharp is one AOP library for .Net.

Sean Carpenter