I found a nice solution for the issue I was facing. Normally when we host a WCF endpoint this is the code we follow.
ServiceHost serviceHost = new ServiceHost(typeof(IService))
Here you pass in the type of the interface you expose to the ServiceHost instance. Instead of this approach, you can make use of the second overload of the ServiceHost constructor which takes in an instantiated object! Now the code looks like this
ServiceImplementation implementation1 = new ServiceImplementation();
ServiceHost serviceHost = new ServiceHost(implementation1);
Only thing to note here is that you need to mark your implementation instance mode as a ‘InstanceContextMode.Single‘, effectively making it a Singlreton.
Now the way it solves my problem is that I use my implementation class to pass any metadata from the host to the implementation. My code now looks like this.
// Create a metadata class just to hold your data.
public class MetaData
{
public MetaData(string data1,int data2)
{
Data1 = data1;
Data2 = data2;
}
public string Data1 { get; set; }
public int Data2 { get; set; }
}
// Just pass in the instance to the host.
MetaData metaData = new MetaData("D1", 100);
ServiceImplementation implementation1 = new ServiceImplementation(metaData);
ServiceHost serviceHost = new ServiceHost(implementation1);
// My Implementation looks like this
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
internal class ServiceImplementation : IService
{
private MetaData m_MetaData;
public ServiceImplementation(MetaData metaData)
{
m_MetaData = metaData;
}
public string Ping(string name)
{
return m_MetaData.Data1;
}
}
See that you have all your meta data in the member ‘m_MetaData’.