lundi 21 novembre 2022

Refactoring a WCF Trusted Facade

I'm attempting to refactor a "trusted facade" which currently wraps over 50 service calls to the backend. All calls have different signatures, but everything else is being repeated. The issue with the existing calls was that there was no attempt made to manage the connections, resulting in ephemeral ports remaining in the "BOUND" state.

ORIGINAL CODE:

public class ReportWeb : IReportWeb
{
    ReportService.ReportClient client = new ReportClient();
    ...
    
    public string[] GetData() => client.GetData();
}

NEW CODE:

private ChannelFactory<IReportService> _factory = null;
private IReportService _proxy = null;

private void OpenProxy()
{
    _factory = new ChannelFactory<IReportService>("NetTcpBinding_IReportService");
    _proxy = _factory.CreateChannel();
}

private void CloseProxy()
{
    ((IClientChannel)_proxy).Close();
    _factory.Close();
}

public string[] GetData()
{
    string[] results = null;

    try
    {
        OpenProxy();
        results = _proxy.GetData();
        CloseProxy();
    }
    catch (Exception exception)
    {
        bool faulted = _factory.State == CommunicationState.Faulted;
        _factory.Abort();

        if (faulted)
        {
            throw new ApplicationException(exception.Message);
        }
        else
        {
            throw;
        }
    }
    return results;
}

There are over fifty other methods like GetData() with different signatures. They will all be identical except for the service call in each, which will vary in params and return type. I need a more abstract, or generic, way of coding this and thus adhere to the DRY principle. Would Func<T, TResult> Delegate be appropriate here? Either way, can someone suggest a best approach here with some stub code to illustrate?

Aucun commentaire:

Enregistrer un commentaire