WCF客户端 - 最佳实践

时间:2012-09-17 15:35:52

标签: c# wcf

我只想听听您关于WCF客户端实施的意见。

我有一台提供SecurityManager等服务的服务器。 此服务在Interface ISecurityManager中定义,并在Class SecurityManager中实现。

到目前为止一切都很好。 在客户端,我想通过一个单独的Class实现服务调用。我的问题是我是否也在实现相同ISecurityManager接口的SecurityManager类中执行此操作?

这是最佳做法?

3 个答案:

答案 0 :(得分:2)

我建议使用通用Wrapper进行WCF调用。 因此,每次您需要进行WCF调用时,您都可以这样做:

var invoker = new ServiceInvoker();
        var result = invoker.InvokeService<ISecurityManager, MyObjectReturnType>(
            proxy => proxy.DoSomething(myParameters));
        return result;

我使用ServiceInvoker来创建频道并管理内部会发生的任何异常。它使用ISecurityManager协定创建一个通道,返回类型为MyObjectReturnType,并带有DoSomething操作(来自ISecurityManager合同的方法)。 您可以将此解决方案与所有接口一起使用,而无需任何额外的类实现!

InvokeService将是这样的:

public TResult InvokeService<TServiceContract, TResult>(Func<TServiceContract, TResult> invokeHandler) where TServiceContract : class
    {
        ICommunicationObject communicationObject;
        var arg = CreateCommunicationObject<TServiceContract>(out communicationObject);
        var result = default(TResult);
        try
        {
            result = invokeHandler(arg);
        }
        catch (Exception ex)
        {
            Logger.Log(ex);
            throw;
        }

        finally
        {
            try
            {
                if (communicationObject.State != CommunicationState.Faulted)
                    communicationObject.Close();
            }
            catch
            {
                communicationObject.Abort();
            }
        }
        return result;
    }

private TServiceContract CreateCommunicationObject<TServiceContract>(out ICommunicationObject communicationObject)
        where TServiceContract : class
    {
        //Create the Channel
        // ICommunicationObject is an out parameter for disposing purposes 
        return channel;
    }

答案 1 :(得分:2)

Visual Studio生成器

您可以要求Visual Studio为您构建客户端,右键单击您的客户端项目并添加Service Reference。这是一个对话框,您可以在其中键入服务URL或从解决方案中发现它。

创建客户端

您可以构建从ClientBase<ISecurityManager>, ISecurityManager继承的客户端类。作为此客户端类的操作示例:

public void ExampleMethod(int id)
{
   Channel.ExampleMethod(id);
}

像真人一样

或者没有任何客户端类,只需调用它:

ServiceInvokerinvoker invoker = new ServiceInvoker(); 
var result = invoker.InvokeService<ISecurityManager, ReturnType>(     proxy => proxy.ExampleMethod(1) ); 

假设您已经配置了ISecurityManager客户端,最后两个选项:

<client>     
<endpoint name="ServiceName" 
address="http://ServiceName.test/Service" 
binding="basicHttpBinding"   
contract="ISecurityManager" /> 
</client> 

答案 2 :(得分:0)

要通过“通过单独的类”实现服务调用,您只需使用svcutil.exe或visual studio从正在运行的服务实例生成服务引用。

这将生成一组服务合同中的类型,这些类型将与包含服务合同和实现的程序集完全“分离”。

相关问题