I have recently started to write my own ChannelFactory wrapper to call my WCF service instead of relying on the auto generated code from visual studio
Previously, with the auto generated proxies, I was able to do this for error checking:
protected AccessControlServiceClient AccessControlService
{
get
{
// Check if not initialized yet
if (HttpContext.Current.Session["AccessControlServiceClient"] == null)
HttpContext.Current.Session["AccessControlServiceClient"] = new AccessControlServiceClient();
// If current client is 'faulted' (due to some error), create a new instance.
var client = HttpContext.Current.Session["AccessControlServiceClient"] as AccessControlServiceClient;
if (client.State == CommunicationState.Faulted)
{
try { client.Abort(); }
catch { /* no action */ }
client = new AccessControlServiceClient();
HttpContext.Current.Session["AccessControlServiceClient"] = client;
}
return client;
}
}
How should I handle this for ChannelFactor? What are the best practices to handle, and re-create the channel should something go wrong? e.g., intermittent network connection, session time out, etc.
This is how my code looks like currently:
Snippet from ProxyBase.cs - creating the channel
private void Initialise()
{
lock (_sync)
{
if (_channel != null) return;
_channel = new ChannelFactory<T>(_serviceEndPointUri).CreateChannel();
}
}
UserManagementServiceClient.cs - IUserManagementService is the WCF contract
public class UserManagementServiceClient : ProxyBase<IUserManagementService>
{
public UserManagementServiceClient(string serviceEndPointUri)
: base(serviceEndPointUri)
{
}
public TokenResponse GetToken(TokenRequest request)
{
return Channel.GetToken(request);
}
public LoginResponse Login(LoginRequest request)
{
return Channel.Login(request);
}
public LogoutResponse Logout(LogoutRequest request)
{
return Channel.Logout(request);
}
}
And finally, this is how I'm calling it in my MVC project
protected UserManagementServiceClient UserManagementService
{
get
{
// Check if not initialized yet
if (HttpContext.Current.Session["UserManagementServiceClient"] == null)
HttpContext.Current.Session["UserManagementServiceClient"] = new UserManagementServiceClient("NetTcpBinding_UserManagementService");
var client = HttpContext.Current.Session["UserManagementServiceClient"] as UserManagementServiceClient;
return client;
}
}
So presently, whenever the default 10 mins session is up, I get an error because the channel has already closed.
How can I harden my code such that it takes care of network disconnections/session timeouts etc?