Friday, May 25, 2012

How to create a WCF Data Service with ASP.Net Dynamic Routing (Without .SVC Extension)

This article explains how to host/create  WCF Data Service using   ASP.Net Dynamic routing (i.e. without .svc extension) that is much more power full then legacy .svc based hosting
Alternative Titles
How to Create A WCF Data Service with out .SVC extension
WCF Data service and ASP.Net Dynamic Routing
Problem is detail 
By default WCF Data Service templates provided by Visual studio creates  a .svc file when you add a WCF Data Service. This svc file actually host your data service class. This hosting model is rigid and can not be changed at run time.
Solution
We can resister the data service in Global.assx file using ASP.Net RoutingTable table and DataServiceHostFactory 
Advantage of  Dynamic  Routing 
There are several advantage of dynamic routing and it can be leverage to solve some typical problem such as loading your data service class at run time based on database setting at run time
Solution Step By Step 
  1. Create a blank asp.net solution 
  2. Use any data base on your system ad create a EXMX for the same (Sample used Northwind)
  3. Add a WCF Data Service (WcfDataService1.svc)  and make it up and running by setting init function as below 
    public static void InitializeService(DataServiceConfiguration config)
            {
                // TODO: set rules to indicate which entity sets and service operations are visible, updatable, etc.
                // Examples:
                config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);
                // config.SetServiceOperationAccessRule("MyServiceOperation", ServiceOperationRights.All);
                config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
            }
  4. Now Create a duplicate of "WcfDataService1.svc.cs" and WcfDataService1.cs and include in the project 
  5. Exclude "WcfDataService1.svc" from project 
  6. No add a Global.asax file in your application (if not already added)
  7. Add reference to "System.ServiceModel.Activation.dll" in the project 
  8. Add Routing entry to your global.asax file as below 
    protected void Application_Start(object sender, EventArgs e)
            {
               RouteTable.Routes.Add(new ServiceRoute("WcfDataService1", new DataServiceHostFactory(), typeof(WcfDataService1)));
                //Other code if any
            }
  9. Resolve the references as required 
  10. service is ready to use you can navigate to http://localhost:8080/WcfDataService1/

No comments:

Post a Comment