摘要:Abstracting WCF Service Calls in Silverlight 3
While working with WCF in Silverlight is a blessing, it is also a challenge because of the way Silverlight manages service references. There are often extra steps required to ensure a service is Silverlight compatible, then additional considerations relative to making the service consumable on the Silverlight side and ensuring security concerns are met, etc. The purpose of this post is to provide a relatively simple and lightweight framework for abstracting the services in your applications to provide a more solid foundation for using them.
The service fundamentally begins on the web server side. Silverlight provides additional templates including a "Silverlight-enabled WCF service." Use this to add a new service reference. This is the first place that the fun can begin.
Despite the friendly sounding name, I've actually had the designer add a service and then declare custom bindings in the web.config with a mode of binary. This isn't something Silverlight knows how to consume. After receiving the ambiguous "NotFound" error and then digging deeper and finding my service was causing a "415 unsupported media type" error in the Silverlight client, I realized my service had generated incorrectly.
The first step was to dig into the web.config and find the service behaviors for my service. The "basicHttpBinding" is the one Silverlight is friendly with, something custom or binary will not. This snippet of web.config demonstrates some of the fundamentals for having the service correct on the server side:
01.
<
system.serviceModel
>
02.
<
serviceHostingEnvironment
aspNetCompatibilityEnabled
=
"true"
/>
03.
<
behaviors
>
04.
<
serviceBehaviors
>
05.
<
behavior
name
=
"Silverlight.Service.CustomServiceBehavior"
>
06.
<
serviceMetadata
httpGetEnabled
=
"true"
/>
07.
<
serviceDebug
includeExceptionDetailInFaults
=
"false"
/>
08.
</
behavior
>
09.
</
serviceBehaviors
>
10.
</
behaviors
>
11.
<
services
>
12.
<
service
behaviorConfiguration
=
"Silverlight.Service.CustomServiceBehavior"
13.
name
=
"Silverlight.Service.CustomService"
>
14.
<
endpoint
address
=
""
binding
=
"basicHttpBinding"
contract
=
"Silverlight.Service.ICustomService"
/>
15.
<
endpoint
address
=
"mex"
binding
=
"mexHttpBinding"
contract
=
"IMetadataExchange"
/>
16.
</
service
>
17.
</
services
>
18.
</
system.serviceModel
>
The basics: aspNetCompatibilityEnabled, basicHttpBinding, and the "mex" binding for meta data exchange. Now we're good and can publish this somewhere to reference from the Silverlight client.
On the client, things get more interesting. You could hard code the endpoint if you knew the location it was being published to, but I needed something much more flexible. What I did know was that the client would always be in a folder relative to the web host with the services, so by extracting my local Uri, I can recreate the service Uri on the fly. What was bothering me was doing this over and over for each service, so I finally created a generic BaseService
class.
The class is based on the client and channel for the service. From this, it knows how to construct a url. Because my service named "CustomService" is actually at "Silverlight/Service/CustomService.svc", a little bit of parsing the host and changing the endpoint is all that is needed.
Here is the class:
01.
public
abstract
class
BaseService<TClient,TChannel> : ClientBase<TChannel> where TClient: ClientBase<TChannel>,
new
() where TChannel:
class
02.
{
03.
private
const
string
BASE_SERVICE =
"Silverlight/Service/{0}.svc"
;
04.
05.
private
static
readonly
string
_baseUri;
06.
07.
static
BaseService()
08.
{
09.
_baseUri = System.Windows.Browser.HtmlPage.Document.DocumentUri.AbsoluteUri;
10.
int
lastSlash = _baseUri.LastIndexOf(
"/"
);
11.
_baseUri = _baseUri.Substring(0, lastSlash+1);
12.
}
13.
14.
private
readonly
TClient _channel;
15.
16.
protected
BaseService()
17.
{
18.
if
(_baseUri.Contains(
"http"
))
19.
{
20.
Binding binding =
new
BasicHttpBinding();
21.
EndpointAddress endPoint =
22.
new
EndpointAddress(
string
.Format(
"{0}{1}"
, _baseUri,
23.
string
.Format(BASE_SERVICE,
typeof
(TChannel).Name)));
24.
_channel = (TClient)Activator.CreateInstance(
typeof
(TClient),
new
object
[] {binding, endPoint});
25.
}
26.
else
27.
{
28.
_channel = Activator.CreateInstance<TCLIENT>();
29.
}
30.
}
31.
32.
protected
TClient _GetClientChannel()
33.
{
34.
return
_channel;
35.
}
36.
}
Basically, the service encapsulates creating the client channel for communicating with the service. The static constructor takes path to the silverlight application and then using string manipulating to find the virtual directory it is hosted in (note if you are running the client in a subfolder, you'll have to trim more slashes to get back to the application root).
Note the use of the Activator
to instantiate new objects that are typed to the channel/client we need. The first passes an object[] array, which causes the activator to find the constructor that best matches the parameters, in this case we are basically doing this:
_channel = new CustomServiceClient(binding, endpoint);
When the service is constructed, it checks to see the the base URI contains "http." The reason we do this is because when you run debug, the URI is actually on the file system (file:
). We assume your default set up for the endpoint is sufficient for debugging and simply instantiate the client without any parameters. If, however, you are running in a web context, the endpoint is overridden with the reconstructed path. Note that we take the name of the channel and then format it into the path so that a channel called CustomService gets mapped to Silverlight/Service/CustomService.svc
.
I then created a special event argument to handle the completion of a service call. It will pass back the entity that the service references, as well as the error object, so the client can process as needed:
01.
public
class
ServiceCompleteArgs<T> : EventArgs where T:
class
02.
{
03.
public
T Entity {
get
;
set
; }
04.
05.
public
Exception Error {
get
;
set
; }
06.
07.
public
ServiceCompleteArgs(T entity, Exception e)
08.
{
09.
Entity = entity;
10.
Error = e;
11.
}
12.
}
Now we can inherit from the base class for our actual service calls. Let's assume CustomService returns an integer. My custom service helper will look like this:
01.
public
class
CustomServiceClientHelper : BaseService<CustomServiceClient, CustomService>
02.
{
03.
public
event
EventHandler<ServiceCompleteArgs<
int
>> CustomServiceCompleted;
04.
05.
public
CustomServiceClientHelper()
06.
{
07.
_GetClientChannel().GetIntegerCompleted += _CustomServiceClientHelperGetIntegerCompleted;
08.
}
09.
10.
public
void
GetInteger()
11.
{
12.
_GetClientChannel().GetIntegerAsync();
13.
}
14.
15.
void
_CustomServiceClientHelperGetIntegerCompleted(
object
sender, GetIntegerCompletedEventArgs e)
16.
{
17.
if
(CustomServiceCompleted !=
null
)
18.
{
19.
int
result = e.Error ==
null
? e.Result : -1;
20.
CustomServiceCompleted(
this
,
new
ServiceCompleteArgs<INT>(result,e.Error));
21.
}
22.
}
23.
}
Now it's very easy for me to reuse the service elsewhere without understanding how the endpoint or data is bound - in my code, putting the result in a TextBlock is as simple as this:
01.
public
void
Init()
02.
{
03.
CustomServiceClientHelper client =
new
CustomServiceClientHelper();
04.
client.CustomServiceCompleted += _ClientCustomServiceCompleted;
05.
client.GetInteger();
06.
}
07.
08.
void
_ClientCustomServiceCompleted(
object
sender, ServiceCompleteArgs<
int
> e)
09.
{
10.
if
(e.Error ==
null
)
11.
{
12.
DisplayTextBlock.Text = e.Entity.ToString();
13.
}
14.
else
15.
{
16.
HandleError(e.Error);
17.
}
18.
}
Now you've got a simple framework for plugging in services and consuming them on the client side that will update its references based on the location it is installed. Of course, there is much more you can do and I suggest the following articles for further reading: