c# - 在 .net 核心中安全地释放依赖注入(inject)的 wcf 客户端

标签 c# wcf dependency-injection .net-core

我想在 .Net Core (2.2) 中使用 Microsoft 的依赖注入(inject)来注入(inject)并安全地释放 WCF 客户端。我在 VS2019 中使用“WCF Web 服务引用提供程序工具”将 WCF 代理类添加到我的解决方案中。使用 Microsoft.Extensions.DependencyInjection 我可以在服务集合中注册客户端,但我似乎无法找到一种 Hook 到发布生命周期事件的方法(可以在各种其他 IoC 框架中完成,例如 Autofac),以添加根据此处描述的 Microsoft 建议进行安全发布的代码:https://learn.microsoft.com/en-us/dotnet/framework/wcf/samples/use-close-abort-release-wcf-client-resources

有没有办法在 .Net Core 框架附带的非常基本的依赖注入(inject)功能中做类似的事情?还是我被迫使用第 3 方 IoC 框架?

伪代码:

所以基本上我想做这样的事情:

// Register the channel factory for the service. Make it
// Singleton since you don't need a new one each time.
services.AddSingleton(p => new ChannelFactory<IWcfService>(
    new BasicHttpBinding(),
    new EndpointAddress("http://localhost/WcfService")));

// Register the service interface using a lambda that creates
// a channel from the factory.
// TODO: need a way to handle proper disposal, e.g. like OnRelease().
services.AddTransient<IWcfService>(p => 
        p.GetService<ChannelFactory<IWcfService>>().CreateChannel())
    .OnRelease(CloseChannel); // <---This is what I would like to do

static void CloseChannel<T>(T channel)
{
    var disp = (ICommunicationObject) channel;
    try
    {
        if (disp.State == CommunicationState.Faulted)
            disp.Abort();
        else
            disp.Close();
    }
    catch (TimeoutException)
    {
        disp.Abort();
    }
    catch (CommunicationException)
    {
        disp.Abort();
    }
    catch (Exception)
    {
        disp.Abort();
        throw;
    }
}

但我需要一种方法来 Hook 服务发布生命周期事件,例如类似于 Autofac 中的 .OnRelease(),因此我可以进行适当的处​​理。

最佳答案

我不知道您是否还需要回复,但为了解决这个问题,我在部分类中实现了处置。

每次处理 wcf 客户端时都会进行正确的清理:

  public partial class MyWcfClient : IDisposable
{
    protected void Dispose(bool disposing)
    {
        if (disposing)
        {
            bool success = false;
            try
            {
                if (State != CommunicationState.Faulted)
                {
                    Close();
                }

                success = true;
            }
            finally
            {
                if (!success)
                {
                    Abort();
                }
            }
        }
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
}

关于c# - 在 .net 核心中安全地释放依赖注入(inject)的 wcf 客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57484418/

相关文章:

c# - 如何确保 C# 项目中配置文件的更改导致 DLL 重建?

c# - 所有的逻辑应该写在 Controller 里面?

c# - 记录 WCF 接口(interface)的最佳方式?

android - 在运行时初始化依赖

当功能跨越 Step 类时,使用 spring 依赖注入(inject)的 Java-Cucumber 测试会抛出 NullPointerException

c# - C# 中的 MemoryStream 导致 Xml 模式验证失败

c# - 来自 ViewModel 的焦点控制

c# - 使用 Microsoft.HttpClient 和 HttpContentExtensions 的通用 POST 请求

wcf - Windows Workflow Foundation (WF) 服务中的 canCreateInstance

c# - 另一种管理这种依赖的方法