IQueryable Repository with StructureMap (IoC) - How do i Implement IDisposable?

If i have the following Repository:

public IQueryable<User> Users()
{
   var db = new SqlDataContext();
   return db.Users;
}

I understand that the connection is opened only when the query is fired:

public class ServiceLayer
{
   public IRepository repo;

   public ServiceLayer(IRepository injectedRepo)
   {
       this.repo = injectedRepo;
   }

   public List<User> GetUsers()
   {
       return repo.Users().ToList(); // connection opened, query fired, connection closed. (or is it??)
   }
}

If this is the case, do i still need to make my Repository implement IDisposable?

The Visual Studio Code Metrics certainly think i should.

I'm using IQueryable because i give control of the queries to my service layer (filters, paging, etc), so please no architectural discussions over the fact that im using it.

BTW - SqlDataContext is my custom class which extends Entity Framework's ObjectContext class (so i can have POCO parties).

So the question - do i really HAVE to implement IDisposable?

If so, i have no idea how this is possible, as each method shares the same repository instance.

EDIT

I'm using Depedency Injection (StructureMap) to inject the concrete repository into the service layer. This pattern is followed down the app stack - i'm using ASP.NET MVC and the concrete service is injected into the Controllers.

In other words:

  1. User requests URL
  2. Controller instance is created, which receives a new ServiceLayer instance, which is created with a new Repository instance.
  3. Controller calls methods on service (all calls use same Repository instance)
  4. Once request is served, controller is gone.

I am using Hybrid mode to inject dependencies into my controllers, which according to the StructureMap documentation cause the instances to be stored in the HttpContext.Current.Items.

So, i can't do this:

   using (var repo = new Repository())
   {
      return repo.Users().ToList();
   }

As this defeats the whole point of DI.

5
задан RPM1984 16 September 2010 в 01:31
поделиться