1

我有一个 .NET 服务参考,我想将它封装到一个单一的、可重用的类中。

我的典型电话看起来像这样:

// instantiate the api and set credentials
ApiClient api = new ApiClient();
api.Credentials.UserName.UserName = "blah";
api.Credentials.UserName.Password = "blahblah";

// operation-specific search parameter object
SomethingSearch search = new SomethingSearch();
search.Key = "blah";

Result[] result = api.GetSomething(search);

api.Close();

其他调用在调用的操作和搜索参数对象中有所不同。

问题是,我不知道如何将 API 操作的名称(即GetSomething()和特定于操作的搜索对象 ( SomethingSearch))传递给类。

我怎么能做到这一点?我不是要求为我完成工作,但我不知道从哪里开始。我相信这Func<T>与代表有关,但我对他们缺乏经验,令人尴尬。

4

2 回答 2

3

我的一位同事开发了这个解决方案:

/// <summary>
/// Proxy for executing generic service methods
/// </summary>
public class ServiceProxy
{
    /// <summary>
    /// Execute service method and get return value
    /// </summary>
    /// <typeparam name="C">Type of service</typeparam>
    /// <typeparam name="T">Type of return value</typeparam>
    /// <param name="action">Delegate for implementing the service method</param>
    /// <returns>Object of type T</returns>
    public static T Execute<C, T>(Func<C, T> action) where C : class, ICommunicationObject, new()
    {
        C svc = null;

        T result = default(T);

        try
        {
            svc = new C();

            result = action.Invoke(svc);

            svc.Close();
        }
        catch (FaultException ex)
        {
            // Logging goes here
            // Service Name: svc.GetType().Name
            // Method Name: action.Method.Name
            // Duration: You could note the time before/after the service call and calculate the difference
            // Exception: ex.Reason.ToString()

            if (svc != null)
            {
                svc.Abort();
            }

            throw;
        }
        catch (Exception ex)
        {
            // Logging goes here

            if (svc != null)
            {
                svc.Abort();
            }

            throw;
        }

        return result;
    }
}

及其使用示例:

public class SecurityServiceProxy
{

    public static UserInformation GetUserInformation(Guid userId)
    {
        var result = ServiceProxy.Execute<MySecurityService, UserInformation>
        (
            svc => svc.GetUserInformation(userId)
        );

        return result;
    }

    public static bool IsUserAuthorized(UserCredentials creds, ActionInformation actionInfo)
    {
        var result = ServiceProxy.Execute<MySecurityService, bool>
        (
            svc => svc.IsUserAuthorized(creds, actionInfo)
        );

        return result;
    }
 }

MySecurityService在这个假案例中,我们使用了GetUserInformation和中的两种方法IsUserAuthorizedGetUserInformation将 aGuid作为参数并返回一个UserInformation对象。 IsUserAuthorized接受一个UserCredentialsActionInformation对象,并返回一个bool用户是否被授权。

此代理也是缓存可缓存服务调用结果的理想场所。

如果您需要向服务器发送参数,可能会有更通用的方法,但我认为您需要为它创建一个特定的代理。例子:

public interface ISecuredService
{
   public UserCredentials Credentials { get; set; }
}

/// <summary>
/// Proxy for executing generic UserCredentials  secured service methods
/// </summary>
public class SecuredServiceProxy
{
    /// <summary>
    /// Execute service method and get return value
    /// </summary>
    /// <typeparam name="C">Type of service</typeparam>
    /// <typeparam name="T">Type of return value</typeparam>
    /// <param name="credentials">Service credentials</param>
    /// <param name="action">Delegate for implementing the service method</param>
    /// <returns>Object of type T</returns>
    public static T Execute<C, T>(UserCredentials credentials, Func<C, T> action) where C : class, ICommunicationObject, ISecuredService, new()
    {
        C svc = null;

        T result = default(T);

        try
        {
            svc = new C();
            svc.Credentials = credentials;

            result = action.Invoke(svc);

            svc.Close();
        }
        catch (FaultException ex)
        {
            // Logging goes here
            // Service Name: svc.GetType().Name
            // Method Name: action.Method.Name
            // Duration: You could note the time before/after the service call and calculate the difference
            // Exception: ex.Reason.ToString()

            if (svc != null)
            {
                svc.Abort();
            }

            throw;
        }
        catch (Exception ex)
        {
            // Logging goes here

            if (svc != null)
            {
                svc.Abort();
            }

            throw;
        }

        return result;
    }
}
于 2012-07-10T22:28:52.557 回答
1

您可以对大多数 WCF 实现采取类似的方法并创建一个定义 API 功能的接口并将实现隐藏在该接口后面。这是使用您的代码示例的快速示例:

    class APIEngine :IApiProvider
    {
        //...Private stuff & other methods
        T[] Search<T>(SearchArgs args)
        {
           //Error handling ommitted
           T[] result;

           switch(args.SearchType)
           {
               case(SearchType.GetSomething)
                    result = GetSomethingSearch(args.Key);
                    break;
               // and so on
           }     


           api.Close();
          return result;
       }
       Result[] GetSomethingSearch(Key searchKey)
       {   
           ApiClient api = new ApiClient(); 
           api.Credentials.UserName.UserName = "blah";
           api.Credentials.UserName.Password = "blahblah";   

           object SomethingSearch search = new SomethingSearch(); 
           search.Key = searchKey;

           result = api.GetSomething(search);  
       }
    }


class SearchArgs
{
    SearchType SearchType {get; set;} //Enum of search types
    SearchKey Key {get; set;} //SearchKey would be parent class for different key types
{

你可以像任何其他接口一样调用它:

IApiProvider.Search(keyValue);

其他一切都可以在构建过程中设置或稍后通过专用方法重新设置。如果这实际上不能回答您的问题,请告诉我。

编辑:

为参数使用包装器类允许您拥有一个友好的 Search 方法,该方法可以采用任意数量的 Search 类型,方法是根据您的 SearchType 确定正确的类型。

于 2012-07-10T21:40:34.977 回答