tags:

views:

1767

answers:

2

I am hosting a service within a Windows Service.

The following snippet instantiates the ServiceHost object:

Host = new ServiceHost(typeof(Services.DocumentInfoService));

The DocumentInfoService class implements a contract interface that has methods that invoke business objects requiring initialization (actually a connection string). Ideally, I'd like the hosting process to get the connection string from the config file and pass it to a constructor for my service object, DocumentInfoService, which would hold onto it and use it to pass to business objects as needed.

However, the ServiceHost constructor takes a System.Type object -- so instances of DocumentInfoService are created via the default constructor. I did note that there is another constructor method for ServiceHost that takes an object instance -- but the docs indicate that is for use with singletons.

Is there a way for me to get to my object after it is constructed so that I can pass it some initialization data?

+1  A: 

Implement your own ServiceHost. See also http://hyperthink.net/blog/servicehostfactory-vs-servicehostfactorybase/

Mark Cidade
+3  A: 

ServiceHost will create the service instances based on the binding and behaviors configured for the endpoint. There's no particular point in time, where you can rely there is a service instance. Hence, ServiceHost does not expose the service instances.

What you could do is add code to your service object constructor to read the relevant configuration values itself through the ConfigurationManager class.

Of course, if you don't keep your configuration in the app.config, that won't work for you. Alternative approach would be to have a well-known singleton object that the service instances access when created to get the necessary configuration.

And there's also the option of creating your own ServiceHost or your own ServiceHostFactory to control the service instantiation explicitly. This would give you acess to the new service instances at the moment of creation. I would stay away from that option though. It's not worth the effort for your scenario.

Franci Penov
After I posted this question, I remembered that I've done similar things before and had forgotten. I've added a settings file to a library project and then copy the relevant sections of the resultant app.config to the true app.config in the executable project. I'm going to try this here. Thanks!
Decker