当前的OperationContext在WCF Windows Service中为空

本文关键字:Service Windows WCF OperationContext | 更新日期: 2023-09-27 18:02:02

我正在尝试使用WCF和WCF服务器在Windows服务中设置发布/订阅系统。绑定是net.TCP。该服务向客户端提供了一个"订阅"方法,这样客户端就可以注册一个回调处理程序,该事件将从链接到服务器的DLL引发。在Subscribe方法中,我尝试使用OperationContext.Current.GetCallbackChannel方法获取回调通道。当我尝试这个操作上下文。当前属性返回NULL。

谁能告诉我在什么情况下这个属性会返回null?我错过了什么吗?我将在下面包括服务代码和接口代码。我在Visual Studio 2012和目标框架4.5中使用c#。

服务:

namespace WService
{
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
public class WcfPublisherService : IWcfPublisherContract
{
    IOALogic logic = new OAControlExample();
    IWcfSubscriberContract _callback = null;
    public void Subscribe()
    {
        _callback = OperationContext.Current.GetCallbackChannel<IWcfSubscriberContract>();
        logic.BarriersChanged += logic_BarriersChanged;
    }
    public void UnSubscribe()
    {
        logic.BarriersChanged -= logic_BarriersChanged;
    }
    void logic_BarriersChanged(object sender, BarriersChangedEventArgs e)
    {
        _callback.BarriersChanged(e.BarrierLines);
    }
}
}

接口:

namespace WService
{
[ServiceContract(SessionMode = SessionMode.Required, CallbackContract = typeof(IWcfSubscriberContract))]
public interface IWcfPublisherContract
{
    [OperationContract(IsOneWay=false, IsInitiating=true)]
    void Subscribe();
    [OperationContract(IsOneWay = false, IsTerminating=true)]
    void UnSubscribe();
}
public interface IWcfSubscriberContract
{
    [OperationContract(IsOneWay = true)]
    void BarriersChanged(BarrierLines barrierLines);
}
}
客户:

namespace TestClient
{
public partial class Form1 : Form
{
    WcfPublisherService myService
        = new WcfPublisherService();
    ServiceCallback serviceCallback = new ServiceCallback();
    public Form1()
    {
        InitializeComponent();
        serviceCallback.NewMessage += serviceCallback_NewMessage;
    }
    private delegate void serviceCallback_NewMessageDelegate(object sender, NewMessageEventArgs e);
    void serviceCallback_NewMessage(object sender, NewMessageEventArgs e)
    {
        if (textBox1.InvokeRequired)
        {
            textBox1.Invoke(new serviceCallback_NewMessageDelegate(serviceCallback_NewMessage), new object[] {sender, e});
        }
        else
        {
            if (textBox1.Text.Trim().Length > 1)
            {
                textBox1.Text += Environment.NewLine;
            }
            textBox1.Text += e.Msg;
        }
    }
    private void button1_Click(object sender, EventArgs e)
    {
        myService.Subscribe();
    }
    private void button2_Click(object sender, EventArgs e)
    {
        myService.UnSubscribe();
    }
}
[CallbackBehaviorAttribute(UseSynchronizationContext = false)]
class ServiceCallback : IWcfSubscriberContract
{
    public delegate void NewMessageEventHandler(object sender, NewMessageEventArgs e);
    public event NewMessageEventHandler NewMessage;
    protected virtual void OnNewMessage(string msg)
    {
        if (NewMessage != null)
        {
            NewMessage(this, new NewMessageEventArgs(msg));
        }
    }
    public void BarriersChanged(OA.BarrierLines barrierLines)
    {
        OnNewMessage("new barrier lines");
    }
}
public class NewMessageEventArgs : EventArgs
{
    public NewMessageEventArgs(string msg)
    {
        this.Msg = msg;
    }
    public string Msg { get; set; }
}
}

* * * * * * * * * 新编辑 * * * * * * * * * * * * * * * 感谢SalientBrain的建议,我已经对我的项目做了相当大的改变,因为我意识到服务必须长时间运行,即使没有客户端连接,也要持续运行,所以我把它改成了单例。即便如此,我最初的问题仍然存在。SalientBrain要求查看我的配置文件,所以我将在下面包括它以及所有其他相关文件。为了节省空间,我把它去掉了,但我不认为我去掉了什么重要的东西。错误发生在PulisherService类的Subscribe方法中。我希望这是我在配置文件中做的一些愚蠢的事情。好的,在这里:

配置:

    <configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
    <system.serviceModel>
        <behaviors>
            <serviceBehaviors>
                <behavior name="WService.WCFPublisherServiceBehavior">
                    <serviceMetadata httpGetEnabled="false" httpsGetEnabled="false" />
                    <serviceDebug includeExceptionDetailInFaults="false" />
                </behavior>
            </serviceBehaviors>
        </behaviors>
        <services>
            <service behaviorConfiguration="WService.WCFPublisherServiceBehavior"
                name="WService.WcfPublisherService">
                <endpoint address="" binding="netTcpBinding" bindingConfiguration=""
                    name="NetTcpBindingEndpoint" contract="WService.IWcfPublisherContract">
                    <identity>
                        <dns value="localhost" />
                    </identity>
                </endpoint>
                <endpoint address="mex" binding="mexTcpBinding" bindingConfiguration=""
                    name="MexTcpBindingEndpoint" contract="IMetadataExchange" />
                <host>
                    <baseAddresses>
                        <add baseAddress="net.tcp://localhost:8523/Publisher" />
                    </baseAddresses>
                </host>
            </service>
        </services>
    </system.serviceModel>
</configuration>

WcfContracts:

    namespace WService
{
    [ServiceContract(SessionMode = SessionMode.Allowed, CallbackContract = typeof(IWcfSubscriberContract))]
    public interface IWcfPublisherContract
    {
        [OperationContract(IsOneWay=false)]
        void Subscribe(string key);
        [OperationContract(IsOneWay = false)]
        void UnSubscribe(string key);
    }
    public interface IWcfSubscriberContract
    {
        [OperationContract(IsOneWay = true)]
        void BarriersChanged(BarrierLines barrierLines);
    }
}

WcfService:

    namespace WService
{
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)]
    public class WcfPublisherService : IWcfPublisherContract
    {
        private static WcfPublisherService _instance = null;
        private IOALogic _logic = null;
        private Dictionary<string, IWcfSubscriberContract> _callbacks
            = new Dictionary<string, IWcfSubscriberContract>();
        private ReaderWriterLock _callbacksLock = new ReaderWriterLock();
        private WcfPublisherService() { }
        public static WcfPublisherService TheInstance()
        {
            if (_instance == null)
            {
                _instance = new WcfPublisherService();
            }
            return _instance;
        }
        public void StopWcf()
        {
            _logic.StopRequest();
        }
        public void StartWcf(IOALogic logic)
        {
            _logic = logic;
            _logic.BarriersChanged += logic_BarriersChanged;
            ThreadPool.QueueUserWorkItem(new WaitCallback(StartWork), null);
        }
        public void StartWork(object state)
        {
            _logic.Run();
        }
        public void Subscribe(string key)
        {
            OperationContext context = OperationContext.Current;
            // The above line returns null ***********************************************
            _callbacksLock.AcquireWriterLock(2000);
            if (_callbacksLock.IsWriterLockHeld)
            {
                _callbacks.Add(key, context.GetCallbackChannel<IWcfSubscriberContract>());
                // The above line throws a null execption because context is null  ********
                _callbacksLock.ReleaseWriterLock();
            }
        }
        public void UnSubscribe(string key)
        {
            _callbacksLock.AcquireWriterLock(2000);
            if (_callbacksLock.IsWriterLockHeld)
            {
                _callbacks.Remove(key);
                _callbacksLock.ReleaseWriterLock();
            }
        }
        void logic_BarriersChanged(object sender, BarriersChangedEventArgs e)
        {
            _callbacksLock.AcquireReaderLock(1000);
            if (_callbacksLock.IsReaderLockHeld)
            {
                try
                {
                    foreach (IWcfSubscriberContract callback in _callbacks.Values)
                    {
                        callback.BarriersChanged(e.BarrierLines);
                    }
                }
                finally
                {
                    _callbacksLock.ReleaseReaderLock();
                }
            }
        }
    }
}

WindowsService:

    namespace WService
{
    public partial class WService : ServiceBase
    {
        internal static ServiceHost _serviceHost = null;
        internal static IOALogic _logic = new OAControlExample();
        public WService()
        {
            InitializeComponent();
        }
        protected override void OnStart(string[] args)
        {
            if (_serviceHost != null)
            {
                _serviceHost.Close();
            }
            _serviceHost = new ServiceHost(WcfPublisherService.TheInstance());
            WcfPublisherService.TheInstance().StartWcf(_logic);
            _serviceHost.Open();
        }
        protected override void OnStop()
        {
            if (WcfPublisherService.TheInstance() != null)
            {
                WcfPublisherService.TheInstance().StopWcf();
            }
            if (_serviceHost != null)
            {
                _serviceHost.Close();
                _serviceHost = null;
            }
        }
    }
}

TestForm:

    namespace TestClient
{
    public partial class Form1 : Form
    {
        ServiceCallback serviceCallback = new ServiceCallback();
        public Form1()
        {
            InitializeComponent();
            serviceCallback.NewMessage += serviceCallback_NewMessage;
        }
        private delegate void serviceCallback_NewMessageDelegate(object sender, NewMessageEventArgs e);
        void serviceCallback_NewMessage(object sender, NewMessageEventArgs e)
        {
            if (textBox1.InvokeRequired)
            {
                textBox1.Invoke(new serviceCallback_NewMessageDelegate(serviceCallback_NewMessage), new object[] {sender, e});
            }
            else
            {
                if (textBox1.Text.Trim().Length > 1)
                {
                    textBox1.Text += Environment.NewLine;
                }
                textBox1.Text += e.Msg;
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            serviceCallback.Subscribe();
        }
        private void button2_Click(object sender, EventArgs e)
        {
            serviceCallback.Unsubscribe();
        }
    }
}

TestCallbackClass:

    namespace TestClient
{
    [CallbackBehaviorAttribute(UseSynchronizationContext = true)]
    class ServiceCallback : IWcfSubscriberContract
    {
        WcfPublisherService myService
            = WcfPublisherService.TheInstance();
        string callbackKey = Guid.NewGuid().ToString();
        public delegate void NewMessageEventHandler(object sender, NewMessageEventArgs e);
        public event NewMessageEventHandler NewMessage;
        protected virtual void OnNewMessage(string msg)
        {
            if (NewMessage != null)
            {
                NewMessage(this, new NewMessageEventArgs(msg));
            }
        }
        public void Subscribe()
        {
            try
            {
                myService.Subscribe(callbackKey);
            }
            catch (Exception ex)
            {
                OnNewMessage("exception: " + ex.Message);
            }
        }
        public void Unsubscribe()
        {
            try
            {
                myService.UnSubscribe(callbackKey);
            }
            catch (Exception ex)
            {
                OnNewMessage("exception: " + ex.Message);
            }
        }
        public void BarriersChanged(OAInterface.BarrierLines barrierLines)
        {
            OnNewMessage("new barrier lines");
        }
    }
    public class NewMessageEventArgs : EventArgs
    {
        public NewMessageEventArgs(string msg)
        {
            this.Msg = msg;
        }
        public string Msg { get; set; }
    }
}

当前的OperationContext在WCF Windows Service中为空

如评论中所讨论的,如果您直接创建服务类型的实例—与WCF代理/clientchannel相反—然后在其上调用方法,则没有OperationContext。当您的操作在服务中运行时,WCF提供了一个OperationContext实例。

在客户端代码中,代理没有创建通道工厂。服务类实例被创建为类库。

你应该像下面的代码那样使用服务

 ServiceCallback serviceCallback = new ServiceCallback();
 InstanceContext instanceContext = new InstanceContext(serviceCallback);
 var pubsubProxy = new PubSubProxy.WcfPublisherContractClient(instanceContext);
 pubsubProxy.Subscribe();

当服务运行时,OperationContext被创建,您可以访问OperationContext。当前

我遇到过这个问题,没有一个解决方案有效,最重要的是,如果你使用

async await 
OperationContext.Current; will be null

我的用法是获取Ip,所以在任何可等待调用

之前使用它
var clientIpAddress = System.Web.HttpContext.Current?.Request?.UserHostAddress;

在异步服务操作的第一个await语句之后,OperationContext。Current可以为空,因为方法体的其余部分可能在不同的线程上运行(并且OperationContext不会在线程之间流动

)。

因此,为了获得它,您可以在任何可等待操作之前编写代码

也许能帮到别人

在我的情况下,我是愚蠢的…

我试图设置

 callback = OperationContext.Current.GetCallbackChannel<IWcfSubscriberContract>();

在CALLBACK函数中,而不是服务器端函数…当在回调函数中-显然没有当前上下文

我有一个类似的问题:在我的情况下,当InstanceContextMode被设置为Single时,WebOperationContext.Current在构造函数中是null。但是,它可以在services/classes方法中使用。