views:

50

answers:

2

I have a class that provide the CRUD operation for an entity.Im using the context as private member accessible for all methods in the class.

  public class CustomerService
  { 
    private CeoPolandEntities context;

    public CustomerService()
    {
        context = new CeoPolandEntities();
    }


    public bool IsCustomerValid(string userName,string password)
    {
        Customer customer;

        customer = context.CustomerSet.FirstOrDefault(c => c.UserName == userName
                                                    && c.Password == password);

        return customer == null ? false : true;
    }

    public bool IsUserNameValid(string userName)
    {
        Customer customer;

        customer = context.CustomerSet.FirstOrDefault(c => c.UserName == userName);

        return customer == null ? true : false;
    }
}

Is this a proper using of context ?? Is it thread safe and concurency safe??

Its a ASP.NET app.

A: 

As long as u have different instances of CustomerService to handle the different requests, u don't need to concern about that. If you happen to have any threads u create yourself, avoid calling multiple methods in the same instance.

eglasius
So if I call in an instance first the load method and then the save method,thats bad ? why ?
no, I mean that if u are creating threads yourself (instead of the ones asp.net create for the request) then its bad i.e. it might still be loading when are already hitting save ... more common is that u are trying to load multiple things with the same context instance all at the same time. Its perfectly k, to use the same instance during a regular asp.net request to load stuff and l8r save.
eglasius
A: 

Contexts aren't thread-safe.

Your current code is fine if:

  1. You change CustomerService to Dispose the Context.
  2. You use one CustomerService per request.
Craig Stuntz
What would be the best way to achieve this ?? Some how automatically..
Implement IDisposable on either the service's base class or your service interface and handle context cleanup in there or if you'd like to have one context per request you could create a static helper class with a method that checks the HttpContext.Current for an instance of the context and if available use it, otherwise create a new context and add it to the current context. If you want functionality outside of the web world as well you could look into attaching to the current thread.
AldenHurley