Adding WCF Service References to multiple projects

2.8k views Asked by At

A couple of very basic questions. I am new to WCF and I am building an application which has a Service Project, A Web Application project and a few Class library projects which I use for Business logic, etc.

I am hosting the WCF locally on my IIS and trying to add service references to the projects.

Question 1. When adding references, should I add a service reference to each project separately or is there a way I can share the same Service reference across the projects?

The reason I ask is because if I add separate references, each reference gets it own namespace, and when I have to pass the same object between the projects, I get an InvalidCastException because each ServiceClient has a different namespace.

Example - Site.Business.XDataService.XDataServiceClient().GetItem() is not the same as Site.Web.XDataService.XDataServiceClient().GetItem()

Question 2. I specified the address of the local service in the class that implements the Service interface as below -

[ServiceBehavior(Namespace = "http://localhost:801/XDataService.svc", IncludeExceptionDetailInFaults = true)]

This doesn't seem right. If I move my code to a different/live environment, I would obviously have to change this part again and recompile. Where can I specify this (Web.Config?) so that I can change this address without having to rebuild my app?

Appreciate any kind of insight. Thanks!

2

There are 2 answers

2
Murph On BEST ANSWER

In answer to the first question, you can put the service reference in its own project and reference that project in all the other projects that need to access that service.

Basically all the service reference is is a lump of .NET code - namespace, class, etc.

Better yet (!) for a WCF service you also get an interface thrown in for free (more or less the same interface that you defined for your service) so you can do nice things in terms of dependency injection making testing etc easier.

1
Kirk Broadhurst On

First question - the service is just like any other code. For example, database access code. Should you put that in every project that needs to access your database? No - you should put it in a project which those other projects can reference.

As for your second question, you're specifying a namespace but I expect you think you're specifying a service endpoint address. The namespace is just like a C# code namespace - it essentially provides further identification and clarity in the event that you have multiple objects with the same name. Normally you'd use a namespace like http://mywebsite.com/MyService/VersionNumberIfRequired or similar.

The address itself is specified in configuration. The address will change depending on environment / deployment location - the namespace shouldn't.