I have a need to run multiple WCF services at the same time, from a single windows service. Each WCF service is basically the same, but has one object specific to that instance. So with the following service class:
public class MyService : IMyContract
{
public MyType MyObject { get; set; }
public MyService(MyType myObject)
{
this.MyObject = myObject;
}
// more here...
}
I hoped I would be able to do something like this:
MyType o1 = new MyType();
MyService s1 = new MyService(o1);
ServiceHost host1 = new ServiceHost(s1, anEndpointAddress);
MyType o2 = new MyType();
MyService s2 = new MyService(s2);
ServiceHost host2 = new ServiceHost(s2, anEndpointAddress);
The problem is, that if you use the ServiceHost constructor that takes an object as its first argument, that object needs to be a singletonInstance, but I need multiple instances.
On the other hand, if I use the constructor which takes a type as its first argument (ServiceHost host = new ServiceHost(typeof(MyService), endpointAddress);), I don’t know how I can set MyObject to a suitable value.
Is there a way to solve this problem?
Thanks, regards, Miel.
I can think of two ways – way 2 will be preferred approach.
Create multiple classes that simply inherits from your service class. For example,
And now host as
If you don;t want singleton then you need to modify these classes such as
and then use another service host constructor
2. I would prefer this approach. Service implementation will not have instance variable holding MyObject. Write custom ServiceHost class such as
Now, host your service on multiple endpoint addresses using
In service methods, use
OperationContext.Current.Hostto get servicehost and from hostm you can get your object.