Including a service reference from a class library

JR. picture JR. · Feb 9, 2009 · Viewed 12.5k times · Source

I have a C# class library and a startup project (a console app). The class library includes a service reference to a web service. When I try to run the project, I get an InvalidOperationException because the startup project isn't reading the class library's app.config, and it's ignoring the service reference. To get it working, I'm forced to add the same service reference to the startup project. Is there any way I can avoid this? Can I make the startup project recognize the class library's service reference and app.config without having to copy it to the startup project?

I've tried adding a link to the app.config from the class library, but that doesn't work. The class library isn't very portable if it requires anyone who uses it to add that service reference to the startup project.

Answer

Andrew Hare picture Andrew Hare · Feb 9, 2009

Think about what you are trying to do - you have two assemblies that you are building:

Library
ConsoleApp

Both of these assemblies have configuration files - I would imagine they look something like this:

Library
    app.config
ConsoleApp
    ConsoleApp.exe.config

When you run ConsoleApp it has no way of reading from or knowing aboout app.config from your Library assembly. The only configuration file that it knows or cares about is ConsoleApp.exe.config. Now it is possible to have configuration files reference each other but this is not the proper solution for what you are trying to do.

Since your Library assembly has no entry point, it will never be loaded into an AppDomain. Since it will never be loaded into an AppDomain its application configuration file will never be used.

What you ought to do is reference Library in ConsoleApp via a project reference. Then move all the relevant configuration data from app.config into ConsoleApp.exe.config as this is the configuration file that will be used by your application.

This will allow you to have to two things you need to invoke methods on your web service

  1. The code in Library that can send and receive SOAP messages.
  2. The configuration metadata that is required by Library to function.