How do I pass parameters to a ServiceHost
Asked Answered
C

1

7

I am doing the following

 //Define the service host
        this._smeediPluginServiceHost = new ServiceHost(typeof(SmeediServiceHost), smeediServiceUri);
        this._smeediPluginServiceHost.AddServiceEndpoint(typeof(ISmeediServiceHost), GetBinding(), smeediServiceUri);
        SetupAndStartWebService(_smeediPluginServiceHost); 


  private void SetupAndStartWebService(ServiceHost serviceHost, ServiceDiscoveryBehavior serviceDiscoveryBehavior = null)
    {
        //Define service behaviours
        ServiceMetadataBehavior serviceMetadataBehavior = new ServiceMetadataBehavior();
        serviceMetadataBehavior.HttpGetEnabled = true;

        //Add the behaviours to the service
        serviceHost.Description.Behaviors.Add(serviceMetadataBehavior);

        if (serviceDiscoveryBehavior != null)
            serviceHost.Description.Behaviors.Add(serviceDiscoveryBehavior);

        serviceHost.Open();
    }  

I need to pass a parameter to the Service and I can't figure out how. I have looked at How do I pass values to the constructor on my wcf service? but couldn't get my head around it. Thanks

Cerebration answered 8/1, 2013 at 0:8 Comment(1)
Could you just read from the app.config file using ConfigurationManager.AppSettings[] within the service itself instead of passing to the constructor?Phantasmal
M
20

If I understand correctly, you want to pass parameters to the constructor of your service implementation class. You can to this by passing an instance of the service class to the ServiceHost constructor, instead of its type. That is:

// Create the service instance
var instance = new SmeediServiceHost("some parameters");

// Define the service host using the above instance
this._smeediPluginServiceHost = new ServiceHost(instance, smeediServiceUri);

Caution - using this approach means you are using a singleton instance of the service class. If you need a new instance per session or per request, then consider using a ServiceHostFactory as described in this answer.

Mervin answered 11/5, 2013 at 0:1 Comment(1)
+1. As an addition, useful article: WCF Service InstancingRadbun

© 2022 - 2024 — McMap. All rights reserved.