How do I pass values to the constructor on my wcf service?

前端 未结 8 480
悲哀的现实
悲哀的现实 2020-11-22 13:09

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,

相关标签:
8条回答
  • 2020-11-22 13:38

    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.

    0 讨论(0)
  • 2020-11-22 13:46

    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.

    0 讨论(0)
提交回复
热议问题