您如何使用 Autofac 从控制台应用程序使用 WCF 服务?

How do you consume WCF services from a console app using Autofac?

所以我有一个控制台应用程序,我在其中使用 Autofac。

我已按如下方式设置我的控制台应用程序:

我有一个 class 我称之为 ContainerConfig - 在这里我有我所有的构建器注册:

public static class ContainerConfig
{
    public static IContainer Configure()
    {
        var builder = new ContainerBuilder();

        builder.Register(c => new MatchRun()).As<MatchRun>).SingleInstance();


        builder.RegisterType<AuditLogic>().As<IAuditLogic>();
        builder.RegisterType<AuditRepository>().As<IAuditRepository>();

        builder.RegisterType<ValidationLogic>().As<IValidationLogic>();

        return builder.Build();
    }
}

我调用我的主要应用程序如下:

    private static void Main(string[] args)
    {
        var container = ContainerConfig.Configure();
        using (var scope = container.BeginLifetimeScope())
        {
            var app = scope.Resolve<IApplication>();

            app.Run(args);

        }
    }

问题是我有一个连接的 WCF 服务。这是我的 AuditRepository。 (仅供参考——我已经多年没有接触过 WCF,所以我已经忘记了我所知道的大部分内容)。

它目前的构造是在我每次调用该客户端时创建和处理代理。这个功能 - 主要是。

看起来像这样:

    public string GetStuff(string itemA, string itemB)
    {
        try
        {
            GetProxy();
            return _expNsProxy.GetStuff(itemA, itemb);
        }
        catch (Exception ex)
        {
            IMLogger.Error(ex, ex.Message);
            throw ex;
        }
        finally
        {
           // CloseProxyConn();
        }
    }

我想知道我能否使用 Autofac 做得更好——创建单个实例与持续打开关闭——还是我完全疯了?我知道我没有完全以正确的方式提出这个问题 - 不是 100% 确定如何实际措辞这个问题。

谢谢

始终创建新代理并在每次调用后将其关闭的方法对 WCF 来说很有用。

否则你可以 运行 进入问题。例如,如果一个服务调用失败,代理创建的通道将进入故障状态,您不能对其进行更多调用,只需中止它即可。然后你需要创建一个新的代理。如果您同时从多个线程调用同一个代理,您也可能会遇到线程问题。

另请检查此 documentation 示例,了解如何在调用 WCF 服务时正确处理错误。

有一个 Autofac.Wcf 包可以帮助您创建和释放频道。检查 documentation here。它使用动态客户端生成方法,您只需提供 WCF 服务的接口,它就会根据接口生成通道。这是一种更底层的方法,因此您必须了解更多正在发生的事情。生成的客户端 class 在后台为您完成此操作。

你需要两个注册,一个是单例的通道工厂:

builder
  .Register(c => new ChannelFactory<IYourWcfService>(
    new BasicHttpBinding(), // here you will have to configure the binding correctly
    new EndpointAddress("http://localhost/YourWcfService.svc")))
  .SingleInstance();

以及每次您请求服务时都会从工厂创建通道的工厂注册:

builder
  .Register(c => c.Resolve<ChannelFactory<IYourWcfService>>().CreateChannel())
  .As<IIYourWcfService>()
  .UseWcfSafeRelease();