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

后端 未结 3 1612
感情败类
感情败类 2020-12-17 03:00

If i have the following Repository:

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

I unde

3条回答
  •  离开以前
    2020-12-17 03:42

    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 GetNewRepository()
    {
        return _repositoryProvider.GetNew();
    }
    

    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> 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.

提交回复
热议问题