tags:

views:

140

answers:

4

We have this pattern everywhere in our code:

using (ServiceAccess ws = new ServiceAccess())
{
//...
//code here to talk to webservice ws
//...
}

How can I replace this boiler plate code with an attribute on the functions that need to talk to the web service? (I'm thinking back to when I did some stuff with Hibernate in Java a long time ago and there was an some "Transation" annotation you could use that would auto-insert some try...catch boiler-plate code into the function.) The using {} is pretty good already but it would be nice to not have it at all... Having an attribute would also help document the function as one that talks the web service as opposed to one that does.

Edit: Would AOP do the trick?

A: 

I think the best you can do is create a shortcut for inserting that code as a snippet. You can't shoehorn a variable declaration into a method via an attribute. Or put another way, attributes can only tell you things about the code. They can't change the code itself.

Joel Coehoorn
+1  A: 

Take a look at aspects in spring.net.

Logicalmind
Yeah I wish our project was using Spring.NET....<sigh> Unfortunately it's pure .NET with no dependencies and it's not a new project so it's too late to bring in Spring.NET. Well unless it was really easy to just use the aop part.
dgrant
You can still do it with proxies. See this:http://www.castleproject.org/dynamicproxy/index.html
Logicalmind
+1  A: 

You can also take a look at PostSharp. I't will let you use attributes to implement aspects, you can use it to achieve what you want.

Fredy Treboux
A: 

"Aspect" type things...this is a way to decorate a given method with code of your choice. If you wanted to dispose e.g. after invocation of your method, the aspect as well as the code would have to have access to the Service. It would also mean that you have little control of the lifetime of the service class.

In some code lately I provide a context to my class through which service instances can be obtained. They are provided to a delegate you may pass. Any disposal can then be made after your closure is left...

DateTime serverTime;
context.UseService<IInfoService>(s=>serverTime = s.GetTime());
flq