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

人走茶凉 提交于 2019-11-27 18:55:20

问题


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.


回答1:


A common approach used with nhibernate is to create your session (ObjectContext) in begin_request (or some other similar lifecycle event) and then dispose it in end_request. You can put that code in an HttpModule.

You would need to change your Repository so that it has the ObjectContext injected. Your Repository should get out of the business of managing the ObjectContext lifecycle.




回答2:


I would say you definitely should. Unless Entity Framework handles connections very differently than LinqToSql (which is what I've been using), you should implement IDisposable whenever you are working with connections. It might be true that the connection automatically closes after your transaction successfully completes. But what happens if it doesn't complete successfully? Implementing IDisposable is a good safeguard for making sure you don't have any connections left open after your done with them. A simpler reason is that it's a best practice to implement IDisposable.

Implementation could be as simple as putting this in your repository class:

public void Dispose()
{
    SqlDataContext.Dispose();
}

Then, whenever you do anything with your repository (e.g., with your service layer), you just need to wrap everything in a using clause. You could do several "CRUD" operations within a single using clause, too, so you only dispose when you're all done.

Update

In my service layer (which I designed to work with LinqToSql, but hopefully this would apply to your situation), I do new up a new repository each time. To allow for testability, I have the dependency injector pass in a repository provider (instead of a repository instance). Each time I need a new repository, I wrap the call in a using statement, like this.

using (var repository = GetNewRepository())
{
    ...
}


public Repository<TDataContext, TEntity> GetNewRepository()
{
    return _repositoryProvider.GetNew<TDataContext, TEntity>();
}

If you do it this way, you can mock everything (so you can test your service layer in isolation), yet still make sure you are disposing of your connections properly.

If you really need to do multiple operations with a single repository, you can put something like this in your base service class:

public void ExecuteAndSave(Action<Repository<TDataContext, TEntity>> action)
{
    using (var repository = GetNewRepository())
    {
        action(repository);
        repository.Save();
    }
}

action can be a series of CRUD actions or a complex query, but you know if you call ExecuteAndSave(), when it's all done, you're repository will be disposed properly.




回答3:


EDIT - Advice Received From Ayende Rahien

Got an email reply from Ayende Rahien (of Rhino Mocks, Raven, Hibernating Rhinos fame).

This is what he said:

You problem is that you initialize your context like this: _genericSqlServerContext = new GenericSqlServerContext(new EntityConnection("name=EFProfDemoEntities"));

That means that the context doesn't own the entity connection, which means that it doesn't dispose it. In general, it is vastly preferable to have the context create the connection. You can do that by using: _genericSqlServerContext = new GenericSqlServerContext("name=EFProfDemoEntities");

Which definetely makes sense - however i would have thought that Disposing of a SqlServerContext would also dispose of the underlying connection, guess i was wrong.

Anyway, that is the solution - now everything is getting disposed of properly.

So i no longer need to do using on the repository:

public ICollection<T> FindAll<T>(Expression<Func<T, bool>> predicate, int maxRows) where T : Foo
        {
            // dont need this anymore
            //using (var cr = ObjectFactory.GetInstance<IContentRepository>())
            return _fooRepository.Find().OfType<T>().Where(predicate).Take(maxRows).ToList();

And in my base repository, i implement IDisposable and simply do this:

Context.Dispose(); // Context is an instance of my custom sql context.

Hope that helps others out.



来源:https://stackoverflow.com/questions/3665336/iqueryable-repository-with-structuremap-ioc-how-do-i-implement-idisposable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!