In my last post, I published a simple ServiceLocator, it may help you to decouple the service consumer from service proxy.
To do this, it is necessary to create a generic interface:
public interface IServiceClient<TServiceInterface> : IDisposable
where TServiceInterface : class
{
TServiceInterface Service { get; }
}
And it is the implementation using the ClientBase of WCF:
public class ServiceClient<TServiceInterface> :
ClientBase<TServiceInterface>,
IServiceClient<TServiceInterface>
where TServiceInterface : class
{
public TServiceInterface Service
{
get { return base.Channel; }
}
void IDisposable.Dispose()
{
try
{
base.Close();
}
catch (CommunicationException)
{
base.Abort();
}
catch (TimeoutException)
{
base.Abort();
}
catch (Exception)
{
base.Abort();
throw;
}
}
}
Then, you can register and use the ServiceClient this way:
// Service Registration
ServiceLocator.Register<IServiceClient<IServiceA>>(() => new ServiceClient<IServiceA>());
// Service Resolving
using (var client = ServiceLocator.Resolve<IServiceClient<IServiceA>>())
{
client.Service.Operation();
}
0 comments:
Post a Comment