Reputation: 29519
I have Windows Service, which is running tasks on timer tick. I also selected to communicate with Windows Service through WCF named pipe channel. I can create WCF Service instance and open it for listening. But how I access objects relying in Windows Service via WCF?
This is what my Windows Service looks like:
public partial class MyService : ServiceBase
{
private ServiceHost m_svcHost = null;
private myObject = null;
...
// Run this method from external WCF client
private void SomeMethod()
{
}
protected override void OnStart(string[] args)
{
if (m_svcHost != null) m_svcHost.Close();
m_svcHost = new ServiceHost(typeof(MyCommunicationService));
m_svcHost.Open();
// initialize and work with myObject
}
protected override void OnStop()
{
if (m_svcHost != null)
{
m_svcHost.Close();
m_svcHost = null;
}
}
}
So what I want, to have access to myObject within WCF Service, when client will make inquiry. Or even run a method on myObject.
Upvotes: 1
Views: 1174
Reputation: 3719
You can create a communication channel between your MyService
(WCF Hosting entity) and the MyCommunicationService
(WCF Service instance) simply using a static property:
//This can be put into a separate DLL if needed.
public interface IMyHostCallbacks
{
void HostCallback(string iSomeDataFromWCFToHost);
}
public static class Host
{
public static IMyHostCallbacks Current;
}
public partial class MyService : ServiceBase, IMyHostCallbacks
{
protected override void OnStart(string[] args)
{
//Set the static callback reference.
Host.Current = this;
if (m_svcHost != null) m_svcHost.Close();
m_svcHost = new ServiceHost(typeof(MyCommunicationService));
m_svcHost.Open();
// initialize and work with myObject
}
//Here you have data from WCF and myObject available.
void IMyHostCallbacks.HostCallback(string iSomeDataFromWCFToHost)
{
//Be careful here.
//Depending on your WCF service and WCF clients this might
//get called simultaneously from different threads.
lock(myObject)
{
myObject.DoSomething(iSomeDataFromWCFToHost);
}
}
}
Surely you can even put the static field into your MyService
class but at least some abstraction between MyService
and MyCommunicationService
would not hurt.
Now, in any place in your MyCommunicationService
you can:
void WCFServiceMethod()
{
Host.Current.HostCallback("some data");
}
Upvotes: 1