0

I have a generic repository that i used to inject in a Job class on the start of the application. This job class intend to run forever in a loop, so the context that repository uses is created just once. The problem is after some days the application was consuming impressives 1gb of memory (in the beggining of the execution it consumes 40mb).

After that, I implemented the Dispose of the DBContext class in the Repository and start to instantiate it in every loop. The problem is solved, but i lost the DIP principle. Here´s the new code:

public class Job
{

   do{
        //some code
        using (var repository = new Repository<User>())
        {
            repository.Save(User);
        }
     }while(true);
} 

The repository:

    public void Save(T entity)
    {
        DbSet.Add(entity);
        _context.SaveChanges();
    }

    private IDbSet<TEntity> DbSet
    {
        get { return _context.CreateSet<TEntity>(); }
    }

Is there some workaround or tip to make the context not consume this memory, instantiating it just once? Or must I need to lost the IoC pattern in that case?

Thanks.

gog
  • 11,788
  • 23
  • 67
  • 129
  • Did you investigate with profiler what is taking your memory? Which objects are instantiated and stay in memory? – Sergey Berezovskiy Oct 15 '15 at 20:00
  • I inject the IRepository in the start of the application. So its never disposed. After i implemented the Dispose method, i need to instantiate it 'by hand' in every loop. – gog Oct 15 '15 at 20:01
  • @Rob I believe he means that instead of injecting repository instance in constructor of Job he has to create new repository instances inside loop – Sergey Berezovskiy Oct 15 '15 at 20:01
  • @SergeyBerezovskiy Its the _context object – gog Oct 15 '15 at 20:03
  • nope. Probably it's some other objects which are referenced by context – Sergey Berezovskiy Oct 15 '15 at 20:05
  • If its not the _context its the DbSet. Wich returns a `Set();` of the DbContext class – gog Oct 15 '15 at 20:06
  • You could still have DIP by making a Context Generator and feeding that in – Alex Krupka Oct 15 '15 at 20:54
  • Rather than injecting repository manually on application start, it is better to have IoC container like Castle Windsor. It will allow to manage lifetime of your dependencies. An example of using it with EF can be found here http://stackoverflow.com/a/15691178 – Andrei Mihalciuc Oct 15 '15 at 21:02

0 Answers0