Holding a Reference to the EF MetadataWorkspace for WCF Services
The title lends itself to a bit thought. Why would the developer feel the need hold a static reference to the MetadataWorkspace of an Entity Framework (EF) model from within their WCF service-oriented applications? The premise being that the WCF services are using EF to serve up data from a backend data store. The answer is twofold. Firstly, loading the EF metadata data into memory is expensive and secondly and most importantly is that EF has a depreciation policy for the metadata cache. The deprecation policy kicks in after the predetermined threshold has been reach (typically 20 minutes of idle time) and removes the metadata from cache. This means that the expense of loading EF metadata into memory is incurred after the idle time has been reached and the deprecation policy has been completed. In laymen terms, the first WCF client call making use of an EF query is subject to a warm-up delay while EF loads the metadata cache. The larger the model, the longer that ‘first’ user of the service must wait for their results. To maintain consistent service response rates, one can hold a reference to the MetadataWorkspace object to ensure that EF doesn’t remove it from its cache.
In short, the solution submitted in this blog pertains to those applications exhibiting lengthy EF startup durations, periodic idle time with their services and a client base that expects predictable service response times.
Background
When an EntityConnection is created, the Entity Framework will load the conceptual, storage and mapping between the conceptual model and the storage model. You can see this if you examine the CSpace (conceptual), SSpace (storage), and CSSpace (conceptual/storage mapping) item collection properties of the MetadataCache instance once the EDM has been loaded. For example, the following code opens an EntityConnection and a QuickWatch of the MetadataWorkspace property of the connection reveals the CSpace, CSSpace, OCSpace, OSpace and SSpace collection properties. With this model we have 274 items in the conceptual model, 314 items in the storage model and 1 item in the conceptual to storage mapping.
Note: the model was created from the AdventureWorksLT2008R2 which is included with the SQL Server 2008R2 product sample databases on codeplex.
Code Snippet
- using (EntityConnection connection = new EntityConnection("Name=AdventureWorksLT2008R2Entities"))
- {
- MetadataWorkspace workspace = connection.GetMetadataWorkspace();
- CountMetaDataItems(workspace);
- }
Model Count
CSpace 274
OSpace 0
SSpace 314
CSSpace 1
OCSpace 0
Note that object model and mapping between the object and conceptual model is not loaded when an EntityConnection is created, the associated item collections are empty. The CountMetaDataItems helper function was created to count the items in each collection.
Code Snippet
- public static void CountMetaDataItems(MetadataWorkspace workspace)
- {
- ItemCollection itemCollection = null;
- // CSpace
- if (workspace.TryGetItemCollection(DataSpace.CSpace, out itemCollection))
- Console.WriteLine("{0} {1}", DataSpace.CSpace.ToString(), itemCollection.Count);
- else
- Console.WriteLine("{0} {1}", DataSpace.CSpace.ToString(), 0);
- // OSpace
- if (workspace.TryGetItemCollection(DataSpace.OSpace, out itemCollection))
- Console.WriteLine("{0} {1}", DataSpace.OSpace.ToString(), itemCollection.Count);
- else
- Console.WriteLine("{0} {1}", DataSpace.OSpace.ToString(), 0);
- // SSpace
- if (workspace.TryGetItemCollection(DataSpace.SSpace, out itemCollection))
- Console.WriteLine("{0} {1}", DataSpace.SSpace.ToString(), itemCollection.Count);
- else
- Console.WriteLine("{0} {1}", DataSpace.SSpace.ToString(), 0);
- // CSSpace
- if (workspace.TryGetItemCollection(DataSpace.CSSpace, out itemCollection))
- Console.WriteLine("{0} {1}", DataSpace.CSSpace.ToString(), itemCollection.Count);
- else
- Console.WriteLine("{0} {1}", DataSpace.CSSpace.ToString(), 0); ;
- // OCSpace
- if (workspace.TryGetItemCollection(DataSpace.OCSpace, out itemCollection))
- Console.WriteLine("{0} {1}", DataSpace.OCSpace.ToString(), itemCollection.Count);
- else
- Console.WriteLine("{0} {1}", DataSpace.OCSpace.ToString(), 0);
- }
So how do we load the object model? The MetadataWorkspace object constructor sound promising. It can load all the .csdl, .msl and ssdl embedded resources from the available assemblies. Let’s give it a try. The following code assumes that model resources are embedded into the executing assembly. If not, the assembly fully qualified name would have to be used together with a known type to return the assembly for the model. An example of which is commented out in the code snippet below. If your model is created in a separate assembly, then you must load the assembly using the assembly qualified name of a type within the model as shown in the lines 1-4 in the code snippet below.
Code Snippet
- //string assemblyQualifiedName = @"AdventureWorksModel.AdventureWorksLT2008R2Entities," +
- // @"AdventureWorksModel, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
- //Type anyModelType = Type.GetType(assemblyQualifiedName);
- //Assembly modelAssembly = Assembly.GetAssembly(anyModelType);
- Assembly modelAssembly = Assembly.GetExecutingAssembly();
- Assembly[] assemblys = { modelAssembly };
- MetadataWorkspace workspace = new MetadataWorkspace(new string[] { @"res://*/"},
- new Assembly[] { Assembly.GetExecutingAssembly() });
- CountMetaDataItems(workspace);
Model Count
CSpace 274
OSpace 0
SSpace 314
CSSpace 1
OCSpace 0
As we can see from the output above, the object model is not loaded. This is because the object model is loaded during view generation or during the first query referencing an entity set. The generated views are then stored inside the object model. So what this means is that we can load the conceptual, storage and conceptual to storage mapping into a MetadataWorkspace instance and then instantiate a new EntityConnection using this MetadataWorkspace instance. The EntityConnection instance can then be used to in the ObjectContext constructor. The only thing left would be to build a LINQ query which becomes converted into a command tree upon which the object model is loaded into cache. A code sample is shown below.
Code Snippet
- string constr = ConfigurationManager.ConnectionStrings["AdventureWorksDB"].ConnectionString;
- System.Data.Common.DbConnection dbConn = new SqlConnection(constr);
- EntityConnection entConn = new EntityConnection(workspace, dbConn);
- using (AdventureWorksLT2008R2Entities dc = new AdventureWorksLT2008R2Entities(entConn))
- {
- var custString = from c in dc.Customers
- select c;
- CountMetaDataItems(dc.MetadataWorkspace);
- }
Model Count
CSpace 274
OSpace 39
SSpace 314
CSSpace 1
OCSpace 37
The output above shows that each of the models has been loaded into the workspace simply because the application reused a reference to the metadata workspace when constructing the EntityConnection. To ensure that the Entity Framework deprecation policies do not remove the metadata from cache after a period of inactivity, hold a static reference to the workspace. I will show this below.
WCF Services Initialization
What’s left is to initialize the EF MetadataWorkspace during startup of the WCF service and hold a static reference which can be used for subsequent EF queries. Fortunately WCF offers a number of trivial options to perform ‘hook’ into the service startup. Below is a list of a number of options, you can read this blog entry for a more descriptive read. I will show a straight forward sample of initializing the MetadataWorkspace by creating custom ServiceHostFactory and ServiceHost classes and implementing the ServiceHostBase.InitializeRunTime() method.
Global.asmx file
- Provides that the WCF service is in ASP.NET compatibility mode
- Called during startup of WCF service
Static AppInitialize() method
- Must be place into the App_Code folder
Implementing ServiceHostFactory and a custom ServiceHost
- override the InitializeRuntime() method
WCF ServiceHostEvents
WCF Sample Implementation
Create a class to hold a global static reference to the MetadataWorkspace which can be globally referenced.
Code Snippet
- public class GlobalWorkspace
- {
- private static object locker = new object();
- private static MetadataWorkspace workSpace = null;
- public static MetadataWorkspace WorkSpace
- {
- get
- {
- lock (locker)
- {
- if (workSpace == null)
- {
- string assemblyQualifiedName = @"AdventureWorksModel.AdventureWorksLT2008R2Entities," +
- @"AdventureWorksModel, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
- Type anyModelType = Type.GetType(assemblyQualifiedName);
- Assembly modelAssembly = Assembly.GetAssembly(anyModelType);
- Assembly[] assemblys = { modelAssembly };
- workSpace = new MetadataWorkspace(new string[] { @"res://*/" }, assemblys);
- string constr = ConfigurationManager.ConnectionStrings["AdventureWorksDB"].ConnectionString;
- System.Data.Common.DbConnection dbConn = new SqlConnection(constr);
- EntityConnection entConn = new EntityConnection(workSpace, dbConn);
- using (AdventureWorksLT2008R2Entities dc = new AdventureWorksLT2008R2Entities(entConn))
- {
- var custString = from c in dc.Customers
- select c;
- workSpace = dc.MetadataWorkspace;
- }
- }
- }
- return workSpace;
- }
- private set {}
- }
- }
Create a WCF Service called AWSales. Modify the interface to include a operational contract, for example GetCustomers(string firstName).
Code Snippet
- [ServiceContract]
- public interface IAWSales
- {
- [OperationContract]
- IList<Customer> GetCustomers(string firstName);
- }
Create a custom service host by deriving from ServiceHost.
Code Snippet
- public class AWSalesServiceHost : ServiceHost
- {
- public AWSalesServiceHost(Type serviceType, params Uri[] baseAddresses)
- : base(serviceType, baseAddresses) { }
- protected override void InitializeRuntime()
- {
- MetadataWorkspace workspace = GlobalWorkspace.WorkSpace;
- base.InitializeRuntime();
- }
- }
Create a custom ServiceHostFactory to instantiate the derived ServiceHost.
Code Snippet
- public class AWSalesServiceHostFactory : ServiceHostFactory
- {
- protected override ServiceHost CreateServiceHost(Type t, Uri[] baseAddresses)
- {
- return new AWSalesServiceHost(typeof(AWSales), baseAddresses);
- }
- public override ServiceHostBase CreateServiceHost(string service,
- Uri[] baseAddresses)
- {
- return new AWSalesServiceHost(typeof(AWSales), baseAddresses);
- }
- }
Implement the service contract and utilize the static reference to MetadataWorkspace when creating your EntityConnections.
Code Snippet
- public class AWSales : IAWSales
- {
- public IList<Customer> GetCustomers(string firstName)
- {
- IList<Customer> customers = null;
- string constr = ConfigurationManager.ConnectionStrings["AdventureWorksDB"].ConnectionString;
- System.Data.Common.DbConnection dbConn = new SqlConnection(constr);
- EntityConnection entConn = new EntityConnection(GlobalWorkspace.WorkSpace, dbConn);
- using (AdventureWorksLT2008R2Entities dc = new AdventureWorksLT2008R2Entities(entConn))
- {
- customers = (from c in dc.Customers
- where c.FirstName == firstName
- select c).ToList<Customer>();
- }
- return customers;
- }
- }
Set the ‘Factory’ attribute in the .svc file.
Code Snippet
- <% @ServiceHost Debug="true" Factory="WcfService.AWSalesServiceHostFactory" %>
Conclusion
The practice suggested in this blog does not pertain to all WCF services. For those smaller or medium size EF models it doesn’t really matter if the Entity Framework deprecates the metadata cache after periods of inactivity, the model will load quite quickly and in the end, the user will never know this occurred. But for larger models, where loading time is much longer and the experience of the end user could be impacted, the technique outlined in this blog may be worth exploring.