如何公开实现接口并使用非托管资源的类?
我有一个关于非托管资源发挥作用时接口使用的问题。 假设我有一个 Web 服务并生成了 WCF 客户端。服务契约如下所示:
[ServiceContract]
public interface ITestService
{
[OperationContract]
string GetData(int value);
}
在客户端,我使用依赖项注入并将 ITestService 接口绑定到 TestServiceClient(使用 svcutil
生成)。但是,当我创建 ITestService 并且它确实是 TestServiceClient 时,它应该以正确的方式进行处理,但客户端不知道它。 你如何处理这个问题?
我考虑过像这样生成代理类:
class TestServiceClientProxy : ITestService
{
#region ITestService Members
public string GetData(int value)
{
var client = new TestServiceClient();
bool success = false;
try
{
var result = client.GetData(value);
client.Close();
success = true;
return result;
}
finally
{
if (!success)
{
client.Abort();
}
}
}
#endregion
}
但是,我不认为代码生成是最好的方法。我应该使用 AOP 框架还是 DynamicProxy?
预先感谢您的帮助。
I have a question regarding use of interfaces when unmanaged resources come to play.
Suppose I have a web service and generated WCF client. Service contract looks like this:
[ServiceContract]
public interface ITestService
{
[OperationContract]
string GetData(int value);
}
On client side I use dependency injection and bind ITestService interface to TestServiceClient (generated with svcutil
). However, when I create ITestService and it really is TestServiceClient it should be disposed in correct way but the clients don't know about it.
How do you deal with this problem?
I thought about generating proxy classes like this:
class TestServiceClientProxy : ITestService
{
#region ITestService Members
public string GetData(int value)
{
var client = new TestServiceClient();
bool success = false;
try
{
var result = client.GetData(value);
client.Close();
success = true;
return result;
}
finally
{
if (!success)
{
client.Abort();
}
}
}
#endregion
}
However, I don't think code generation would be best way to go. Should I use some AOP framework or DynamicProxy?
Thanks in advance for help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
声明您的接口实现 IDisposable,在具体类中实现 Dispose(),您的 DI 提供者将正确处理它。如果您的 DI 提供商不这样做,请寻找新的提供商。
Declare that your interface implements IDisposable, implement Dispose() in the concrete class, and your DI provider will dispose it properly. If your DI provider doesn't do this, find a new one.