1

Spending some time sifting through documentation, I'm trying to figure out the best software architecture with or without the dispose pattern.

I've built the Repository pattern many time over the years, whilst using the dispose pattern which conformed to "best-practise". I actively use Ninject in which has configuration as follows:

/// <summary>
/// Starts the application
/// </summary>
public static void Start()
{
   DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
   DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
   bootstrapper.Initialize(CreateKernel);
}

/// <summary>
/// Load your modules or register your services here!
/// </summary>
/// <param name="kernel">The kernel.</param>
private static void RegisterServices(IKernel kernel)
{
   Bind<DBContext>().ToSelf().InRequestScope();
}

As you can see, we have "OnePerRequestHttpModule" and "InRequestScope" for the DB Context, on the assumption that the "caller" of an object that implements the IDisposable is responsible for the disposing of that object.

Do I ever need to dispose of an object if it's Ninjects responsibility?

I have multiple naïve repositories that injects the context at runtime, with one per http request and the context of "in request scope" thus the context being passed around in the life time of a request.

The joy's of finding deeper understanding.

Tez Wingfield
  • 253
  • 2
  • 12

1 Answers1

0

According to this NInject WIKI article, the answer would be no, if...

https://github.com/ninject/Ninject.Web.Common/wiki/InRequestScope

OnePerRequestModule is an IHttpModule provided by Ninject that will hook the EndRequest callback and Dispose instances associated with ASP.NET's HttpContext.Current as part of the Ninject Kernel's Deactivation of tracked instances for you. You can register it using the following XML in your web.config

(Quoted from the end of the page)

There is a section in the article that discusses ensuring predictable disposal of objects not needed anymore. It talks about stock NInject using the HttpContext as it's scoping object for the kernel. That means that the NInject kernel gets disposed when the context is disposed--but that is not a predictable time.

The OnePerRequestHttpModule disposes of appropriately marked resources when the Request is ended (it listens to the HttpContext.EndRequest callback method).

Since those are steps you took, you should not dispose of them yourself. I'm not sure how well Entity Framework handles multiple dispose calls, but some dispose calls can throw exceptions if the object is already disposed.

Berin Loritsch
  • 45,784
  • 7
  • 87
  • 160
  • Thank you very much, I missed that. I'm glad my thoughts have been solidified, helps avoiding pointless lines... Much appreciated! – Tez Wingfield Mar 26 '18 at 19:24