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,
Mark's answer with the IInstanceProvider
is correct.
Instead of using the custom ServiceHostFactory you could also use a custom attribute (say MyInstanceProviderBehaviorAttribute
). Derive it from Attribute
, make it implement IServiceBehavior
and implement the IServiceBehavior.ApplyDispatchBehavior
method like
// YourInstanceProvider implements IInstanceProvider
var instanceProvider = new YourInstanceProvider(<yourargs>);
foreach (ChannelDispatcher dispatcher in serviceHostBase.ChannelDispatchers)
{
foreach (var epDispatcher in dispatcher.Endpoints)
{
// this registers your custom IInstanceProvider
epDispatcher.DispatchRuntime.InstanceProvider = instanceProvider;
}
}
Then, apply the attribute to your service implementation class
[ServiceBehavior]
[MyInstanceProviderBehavior(<params as you want>)]
public class MyService : IMyContract
The third option: you can also apply a service behavior using the configuration file.
This was a very helpful solution - especially for someone who is a novice WCF coder. I did want to post a little tip for any users who might be using this for an IIS-hosted service. MyServiceHost needs to inherit WebServiceHost, not just ServiceHost.
public class MyServiceHost : WebServiceHost
{
public MyServiceHost(MyService instance, Type serviceType, params Uri[] baseAddresses)
: base(instance, baseAddresses)
{
}
}
This will create all the necessary bindings, etc for your endpoints in IIS.