Re-using WCF service among several Silverlight applications

5 באוקטובר 2011

תגיות: , , , , ,
אין תגובות

image

This article is about creating WCF RIA service in class library assembly instead of in the Silverlight application. For unknown reason (at least for me) most, if not all of the Silverlight samples implement the service logic in the main Silverlight application project. But since MVVM is all about de-coupling and re-using, Those services should be implemented in class library and exposed by the application.

Press here to download demo solution. In this solution you will find a working service as shown above.

Creating the service in class library project

1 Open your application solution.

Add project of type 'Class Library' (Notice not to select 'Silverlight class library').

3 In the newly created project add an item of type 'WCF service'. This file extension is '.cs' and not '.svc'. Don't worry about it at the moment.

image

Visual studio creates a regular WCF service with service contract (interface), service concrete class and relevant attributes.

Add one or more methods to the service.

Exposing the service from the Silverlight application

The following steps should be executed in the Silverlight web project. We are going to create a service which will operate as proxy to the service we created in previous steps.

5 Add a project reference to the WCF service project from the Silverlight web project.

6 Add an item of type 'Silverlight-enabled WCF service'

image

7 Check if a service endpoint was added to 'system.serviceModel' element  in the 'web.config' file. If so, delete the configuration for that service.

Visual studio created regular empty service. Our goal is to use this service as proxy to the service that you created earlier. In the following steps you will convert the service to a proxy using inheritance.

8 Open the file with the extension 'svc.cs' of the newly created service.

9 Remove the class' content as well as the attribute 'ServiceContract'.

10 Inherit from the service class you created in the separate project.

If you have reached this step then you finished creating a service in a class library. You may now create a service reference to the service proxy and use it as all the regular services.

Note, If you followed the instructions carefully you probably noticed that you didn't need to add any configuration to the configuration file 'web.config'. The reason is that Silverlight runtime engine creates dynamic configuration on the fly when a client tries to use the service.

Recap

In this article I demonstrated how you can easily create services in class library assembly. Doing so allow you to re-use the service between applications.

Demo

Press here to download demo solution. In this solution you will find a working service as shown above.

הוסף תגובה
facebook linkedin twitter email

כתיבת תגובה

האימייל לא יוצג באתר. שדות החובה מסומנים *