I would like to pass values into the constructor on the class that implements my service.
However ServiceHost only lets me pass in the name of the type to create,
You can simply create and instance of your Service
and pass that instance to the ServiceHost
object. The only thing you have to do is to add a [ServiceBehaviour]
attribute for your service and mark all returned objects with [DataContract]
attribute.
Here is a mock up:
namespace Service
{
[ServiceContract]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class MyService
{
private readonly IDependency _dep;
public MyService(IDependency dep)
{
_dep = dep;
}
public MyDataObject GetData()
{
return _dep.GetData();
}
}
[DataContract]
public class MyDataObject
{
public MyDataObject(string name)
{
Name = name;
}
public string Name { get; private set; }
}
public interface IDependency
{
MyDataObject GetData();
}
}
and the usage:
var dep = new Dependecy();
var myService = new MyService(dep);
var host = new ServiceHost(myService);
host.Open();
I hope this will make life easier for someone.