gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 03:59:09 27 4
gpt4 key购买 nike

我想在 .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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com