Amir Fahmideh
Amir Fahmideh

Reputation: 465

Error in access to Entity Framework data from WCF service in web and win form application?

I am in the middle of big web application, I use Entity Framework as my data service, now we need some windows application to work with our data, so I want to give them a service with WCF

But when my client wants to get service some error is happened from my public property which I use for caching Entity Model

    public partial class DepositEntities : ObjectContext
    {
        public static DepositEntities Current
        {
            get
            {
                DepositEntities oc = 
                    HttpContext.Current.Items["ObjectContext"] as DepositEntities;

                if (oc == null)
                {
                    oc = new DepositEntities();
                    HttpContext.Current.Items["ObjectContext"] = oc;
                }

                return oc;
            }
        }
    }

I know the problem is from this line, after I debug my code

DepositEntities oc = System.Web.HttpContext.Current.Items["ObjectContext"] as DepositEntities;

When I change my Current property body to some thing like this

public static DepositEntities Current
{
   get
   {
      DepositEntities oc = new DepositEntities();
      return oc;
   }
}

everything is OK when I get data from services I have no problem

But everywhere I have join in my codes I have problem because It thinks there are different data source because of new DepositEntities();

Upvotes: 1

Views: 361

Answers (2)

Olav Nybø
Olav Nybø

Reputation: 11568

Check out "Hosting WCF Services in ASP.NET Compatibility Mode" in wcf service and ASP.NET. It explains how to get a valid HttpContext in a wcf service.

Upvotes: 1

empi
empi

Reputation: 15901

You're most likely experiencing problems because WCF doesn't have HttpContext.Current. Read more about contexts in WCF - this question may be a good start: http://social.msdn.microsoft.com/Forums/en/wcf/thread/27896125-b61e-42bd-a1b0-e6da5c23e6fc.

I also think it would be better for you to manage lifetime of an ObjectContext with a DI Container (ie. Castle Windsor). Thanks to this, it won't be necessary to expose static property Current which is a problem for WCF service, unit tests, etc.

Upvotes: 1

Related Questions