We will present how easy it is to consume data from a WCF service in an Excel add-in.
Objective: Pass a name to a WCF service and get a message saying “Hi name”. This service has been created with the only purpose of illustrate the concept of calling a WCF service from an add-in.
We are using the following AddinX packages:
- AddinX.Bootstrap: Using the extension for Autofac to register WCF service
- AddinX.Configuration: read the appSetting to get the url to the service
- AddinX.Ribbon: Create a tab with buttons to call the WCF service
We will explain the part related to the WCF service, we assume that you are using the packages listed above. You can also download the sample from github or use the following command line.
Application setting for the service URL
In the application configuration file named “WcfSample-AddIn.xll.config”, we included a appSetting named SayHelloServiceUri with value set to the URL of the WCF service.
Registration of the WCF Service
In the package AddinX.Bootstrap.Autofac, we created an extension to allow the registration of WCF service with the ContainerBuilder from Autofac.
The code of this extension is as follow:
We used the code provided on the Autofac documentation for Clients and made it generic so we only have to pass the Interface of the service and the URL to the WCF service.
If we want to register a WCF service with Autofac, we need to write only one line of code:
Consume the service
To use the service, it will be injected by Autofac in classes that have the service interface as input parameter to their constructor.
That’s it! Now you just need to consume the service as the example below