2

I am implementing context in my service as per code below. I need to setup IDisposable correctly as it is not being called.

public class MyWidgetService : WidgetService, IDisposable
{
    private bool _disposed;
    private readonly DBContext _context;

    public MyWidgetService()
    {
        _context = new DBContext();
    }

    public List GetWidgets()
    {
            return _context.stuff().ToList();
    }

    // however dipose is never being called
    public void Dispose()
    {
        Dispose(true);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (!_disposed)
        {
            if (disposing)
            {
                _context.Dispose();
            }
        }
        _disposed = true;
    }
}

I am then using Ninject to serve instances of my widget service

public SomeClass(IWidgetService widgetService)
{         
    _widgetService = widgetService;            
}

I register the widget service with ninject here

private static IKernel CreateKernel()
        {
            var kernel = new StandardKernel();
            try
            {
                kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
                kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
                kernel.Bind<IWidgtetService>().To<WidgetService>();
                kernel.Bind<IWidgetService>().To<WidgetService>();                

                RegisterServices(kernel);
                return kernel;
            }
            catch
            {
                kernel.Dispose();
                throw;
            }
        }
Pod
  • 215
  • 3
  • 10

1 Answers1

0

See the answer to this question:

Guidelines For Dispose() and Ninject

From the post:

Ninject disposes every Disposable object that has another scope other than InTransientScope as soon as the scope object to which the created object is tied is collected by GC. That's why every Disposable object should be Bindd with a scope that is not InTransientScope(). E.g. you can use InParentScope() from the NamedScope extension which will Dispose the object as soon as the object it is injected into is garbage collected.

You are not specifying a scope on your bindings, so they are using transient scope by default. If you use any other scope, you should see Dispose get called.

Community
  • 1
  • 1
Jim Skerritt
  • 4,078
  • 2
  • 27
  • 23