How to initialize a self-service service object in WCF

I host the service on a windows service.

The following snippet creates an instance of the ServiceHost object:

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

The DocumentInfoService class implements a contract interface in which there are methods that call business objects that require initialization (in fact, a connection string). Ideally, I would like the hosting process to get the connection string from the configuration file and pass it to the constructor for my DocumentInfoService service object, which will hold it and use it to transfer business objects as needed.

However, the ServiceHost constructor accepts a System.Type object, so instances of DocumentInfoService are created using the default constructor. I noticed that there is another constructor method for ServiceHost that accepts an instance of an object, but the docs indicate what to use with single points.

Is there a way to get to my object after building it so that I can pass some initialization data to it?

+4
source share
2 answers

ServiceHost will create service instances based on the binding and behavior configured for the endpoint. There is no special moment when you can rely on a service instance. Therefore, ServiceHost does not provide service instances.

What you can do is add code to your service object constructor to read the corresponding configuration parameter values ​​through the ConfigurationManager class.

Of course, if you do not save your configuration in app.config, this will not work for you. An alternative approach would be to have a well-known singleton object accessed by service instances when created in order to obtain the necessary configuration.

It is also possible to create your own ServiceHost or your own ServiceHostFactory to directly control the creation of a service. This will give you access to new instances of the service at the time of creation. However, I would stay away from this option. This is not worth the effort for your scenario.

+4
source

Source: https://habr.com/ru/post/1277547/


All Articles