【发布时间】:2011-01-15 18:32:31
【问题描述】:
在我们的 SharePoint/ASP.NET 环境中,我们有一系列数据检索器类,它们都派生自一个通用接口。我的任务是创建一个可以使用 WCF 与其他 SharePoint 场进行远程通信的数据检索器。我目前实现它的方式是在静态构造函数中创建一个单例ChannelFactory<T>,然后由远程数据检索器的每个实例重用以创建一个单独的代理实例。我认为这会很好用,因为ChannelFactory 只会在应用程序域中实例化一次,它的创建是guaranteed to be thread-safe。我的代码如下所示:
public class RemoteDataRetriever : IDataRetriever
{
protected static readonly ChannelFactory<IRemoteDataProvider>
RequestChannelFactory;
protected IRemoteDataProvider _channel;
static RemoteDataRetriever()
{
WSHttpBinding binding = new WSHttpBinding(
SecurityMode.TransportWithMessageCredential, true);
binding.Security.Transport.ClientCredentialType =
HttpClientCredentialType.None;
binding.Security.Message.ClientCredentialType =
MessageCredentialType.Windows;
RequestChannelFactory =
new ChannelFactory<IRemoteDataProvider>(binding);
}
public RemoteDataRetriever(string endpointAddress)
{
_channel = RemoteDataRetriever.RequestChannelFactory.
CreateChannel(new EndpointAddress(endpointAddress));
}
}
我的问题是,这是一个好的设计吗?我认为一旦创建了ChannelFactory,我就不需要担心线程安全,因为我只是用它来调用CreateChannel(),但我错了吗?它是在改变状态还是在幕后做一些可能导致线程问题的时髦事情?此外,我是否需要在某个地方(静态终结器?)放置一些代码来手动处理 ChannelFactory,或者我可以假设每当 IIS 重新启动时,它都会为我完成所有清理工作?
【问题讨论】:
标签: wcf singleton thread-safety channelfactory static-constructor