Search code examples
wcfentity-frameworkrestentity-framework-5wcf-data-services

How to query the Entity Framework in a WCF Data Services OData Service from within the ServiceAuthorizationManager


My FooData.svc.cs file looks like this: (Take note of the undeclared object CurrentDataSource.)

public class FooData : DataService<FooEntities>
{
    public static void InitializeService(DataServiceConfiguration config)
    {
      // init code
    }

    [WebGet]
    public IQueryable<someStoredProcedure_Result> someStoredProcedure(int param1, int param2)
    {
        return CurrentDataSource.someStoredProcedure(param1, param2).AsQueryable();
    }
}

My Authorizer.cs file looks like this:

public class Authorizer : System.ServiceModel.ServiceAuthorizationManager
{
    protected override bool CheckAccessCore(OperationContext operationContext)
    {
        if (base.CheckAccessCore(operationContext))
        {
            if (IsAuthorized())
                return true;
            else
                return false;
        }
        else
            return false;
    }

    private bool IsAuthorized(OperationContext operationContext)
    {
      // some code here that gets the authentication headers, 
      // etc from the operationContext

      // *********
      // now, how do I properly access the Entity Framework to connect 
      // to the db and check the credentials since I don't have access
      // to CurrentDataSource here
    }
}

Applicable section from Web.config, for good measure:

<system.serviceModel>
  <behaviors>
    <serviceBehaviors>
      <behavior>
        <serviceAuthorization serviceAuthorizationManagerType="MyNamespace.Authorizer, MyAssemblyName" />
      </behavior>
    </serviceBehaviors>
  </behaviors>
</system.serviceModel>

So my question has to do with where you see all the asterisks in the code in Authorizer.cs. What is the recommended way to connect to the Entity Framework from within the ServiceAuthorizationManager since I don't have access to CurrentDataSource there? Do I just establish a separate "connection"? e.g.

using (var db = new MyNamespace.MyEntityFrameworkDBContext())
{
    // linq query, stored proc, etc using the db object
}

To clarify, the above code works just fine. I'm just wondering if it's the correct way. By the way, this is a Visual Studio 2012 WCF Data Services project with .NET 4.5 and Entity Framework 5.


Solution

  • I think you answered your own question. If you are concerned with the creation of DbContext for each IsAuthorized - then unless you are calling this functions hundreds of times during 1 request you should be fine. As mentioned here,here or here recreation of EF context is not only inexpensive operation but also recommended.

    EDIT:

    Please note that DataService constructor is called after IsAuthorized, therefore independent instance of DbContext is the most likely the way to go.