Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.ServiceModel;
- using System.ServiceModel.Security;
- public static class Service
- {
- private static IService _service;
- public static void Invoke(Action<IService> action)
- {
- try
- {
- action(_service);
- }
- catch (MessageSecurityException)
- {
- if (_service.State != CommunicationState.Faulted)
- {
- throw;
- }
- _service.Abort();
- _service = CreateFreshInstance();
- action(_service);
- }
- }
- }
- public class ProxyWrapper<T> where T : ICommunicationObject
- {
- private T _service;
- public ProxyWrapper()
- {
- _service = CreateNewInstance();
- }
- public void Invoke(Action<T> action)
- {
- try
- {
- action(_service);
- }
- catch (MessageSecurityException)
- {
- if (_service.State != CommunicationState.Faulted)
- {
- throw;
- }
- _service.Abort();
- _service = CreateNewInstance();
- action(_service);
- }
- }
- public TResult Invoke<TResult>(Func<T, TResult> func)
- {
- try
- {
- return func(_service);
- }
- catch (MessageSecurityException)
- {
- if (_service.State != CommunicationState.Faulted)
- {
- throw;
- }
- _service.Abort();
- _service = CreateNewInstance();
- return func(_service);
- }
- }
- private T CreateNewInstance()
- {
- Type type = typeof(T);
- return (T)type.GetConstructor(Type.EmptyTypes).Invoke(null);
- }
- }
- ProxyWrapper<ServiceClient> client = new ProxyWrapper<ServiceClient>();
- client.Invoke(s => s.SomeAction());
- int val = client.Invoke<int>(s => s.ReturnsAnInteger());
- //Proxy implements this
- interface IMyService
- {
- void MyMethod();
- }
- //Decorator 1
- public class MyServiceProxyRetryingDecorator : IMyService
- {
- //This is the real proxy that might be faulted
- private realProxy = new RealProxy();
- public void MyMethod()
- {
- ReEstablishProxyIfNecessary();
- //now just pass the call to the proxy, if it errors again,
- //do more handling or let the exception bubble up
- realProxy.MyMethod();
- }
- private void ReEstablishProxyIfNecessary()
- {
- if(realProxy.CommunicationState == CommunicationState.Faulted)
- {
- realProxy.Abort();
- realProxy = new RealProxy();
- }
- }
- }
- //Decorator 2
- public class MyServiceProxyExceptionHandlingDecorator : IMyService
- {
- //This is the real proxy that might be faulted
- private realProxy = new RealProxy();
- public void MyMethod()
- {
- try {realProxy.MyMethod(); }
- catch (ExceptionYouAreInterestedIn ex)
- {
- ReEstablishProxyIfNecessary();
- realProxy.MyMethod(); //do it again
- }
- }
- private void ReEstablishProxyIfNecessary()
- {
- if(realProxy.CommunicationState == CommunicationState.Faulted)
- {
- realProxy.Abort();
- realProxy = new RealProxy();
- }
- }
- }
Add Comment
Please, Sign In to add comment