【问题标题】:How do you consume WCF services from a console app using Autofac?如何使用 Autofac 从控制台应用程序使用 WCF 服务?
【发布时间】:2019-02-21 03:07:10
【问题描述】:

所以我有一个使用 Autofac 的控制台应用程序。

我的控制台应用程序设置如下:

我有一个名为 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% 确定如何实际说出这个问题。

谢谢

【问题讨论】:

    标签: c# wcf autofac


    【解决方案1】:

    在每次调用后始终创建新代理并关闭它的方法对 WCF 很有好处。

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

    请查看此documentation,其中包含调用 WCF 服务时如何正确处理错误的示例。

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

    对于单例的通道工厂,您需要两个注册:

    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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多