在 .NET Core 中,可以使用 ChannelFactory
类来创建和管理 WCF 客户端。下面是一个安全释放依赖注入的 .NET Core WCF 客户端的解决方法:
public interface IMyService
{
Task GetDataAsync(int id);
}
public class MyServiceClient : IMyService, IDisposable
{
private readonly ChannelFactory _factory;
private IMyService _client;
public MyServiceClient(string endpointConfigurationName)
{
_factory = new ChannelFactory(endpointConfigurationName);
_client = _factory.CreateChannel();
}
public async Task GetDataAsync(int id)
{
return await _client.GetDataAsync(id);
}
public void Dispose()
{
if (_client != null)
{
if (_client is IClientChannel channel && channel.State != CommunicationState.Closed)
{
channel.Close();
}
else
{
_client = null;
}
}
if (_factory != null && _factory.State != CommunicationState.Closed)
{
_factory.Close();
}
}
}
Startup.cs
中使用依赖注入将 WCF 客户端注册为服务:public void ConfigureServices(IServiceCollection services)
{
// 注册 WCF 客户端
services.AddScoped(provider =>
{
var configuration = provider.GetRequiredService();
var endpointConfigurationName = configuration["Wcf:EndpointConfigurationName"];
return new MyServiceClient(endpointConfigurationName);
});
// ...
}
public class MyController : Controller
{
private readonly IMyService _myService;
public MyController(IMyService myService)
{
_myService = myService;
}
public async Task Index()
{
var data = await _myService.GetDataAsync(123);
// 处理返回的数据
return View();
}
}
在这个解决方法中,使用了 ChannelFactory
来创建 WCF 客户端,并在 Dispose
方法中关闭和释放相关资源。通过依赖注入,可以更好地管理 WCF 客户端的生命周期,并确保在不再需要时正确地释放资源。