How do I pass parameters to a ServiceHost

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

Answers


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.


Need Your Help

What Content-Type value should I send for my XML sitemap?

xml mime-types sitemap xml-sitemap

I thought I should send "text/xml", but then I read that I should send "application/xml". Does it matter? Can someone explain the difference?

C#: Create a virtual drive in Computer

c# .net virtualization storage virtual-drive

Is there any way to create a virtual drive in "(My) Computer" and manipulate it, somewhat like JungleDisk does it?