Dispose or not dispose injectable instance using Ninject - c#

I have the following code block for configuring Ninject in my solution:
public class NinjectDependencyScope : IDependencyScope
{
private IResolutionRoot resolver;
internal NinjectDependencyScope(IResolutionRoot resolver)
{
Contract.Assert(resolver != null);
this.resolver = resolver;
}
public object GetService(Type serviceType)
{
if (resolver == null)
{
throw new ObjectDisposedException("this", "This scope has already been disposed");
}
return resolver.TryGet(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType)
{
if (resolver == null)
{
throw new ObjectDisposedException("this", "This scope has already been disposed");
}
return resolver.GetAll(serviceType);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
IDisposable disposable = resolver as IDisposable;
if (disposable != null)
{
disposable.Dispose();
}
resolver = null;
}
}
My opinion is that disposable pattern used here, is not neccessary..
IDependencyScope is IDisposable, but I should only cleanup IDisposable members if I am constructing them, but the injected resolver in the constructor does is not owned (created) by my class, and IResolutionRoot does not derive from/implement IDisposable...
Am I right here ?
(check this article about IDisposable pattern for reference)
(edit):
This is in fact a base class, used by the following class, so removing the IDisposable implementation here cannot be done...
public class NinjectDependencyResolver : NinjectDependencyScope, IDependencyResolver
{
private IKernel kernel;
public NinjectDependencyResolver(IKernel kernel)
: base(kernel)
{
this.kernel = kernel;
}
public IDependencyScope BeginScope()
{
return new NinjectDependencyScope(kernel.BeginBlock());
}
}

My experience with Ninject has been that when it comes to managed objects implementing IDisposable, you don't need to worry so much as they will be disposed off eventually.
However, when if you have disposable objects which are wrappers around unmanaged objects (for example a C# class wrapping around an Office Interop Application object), then you need to take greater care as these will be disposed off eventually by Ninject, but you can't reliably say when.
Sometimes you need to clean up these resources quickly, as other parts of your code may rely on these resources being cleaned up already (for example you may be 'using' one of these objects to create a Workbook, and then need to rename the workbook shortly after, by which point you need the Application object to be released).
In this sort of scenario, I may violate DI principle, and just new up the object when I use it, and dispose of it myself.
I guess just test all of this yourself so you know which objects are suitable to use with Ninject, and which aren't and do so accordingly.

I know that this is the case with Autofac. You shouldn't worry about disposing classes that you have resolved from Autofac because it will call dispose for you. I am pretty sure that Ninject would be similar.

The following miminal implimentation is correct (provided that neither this class or a class that derives from it uses UNmanaged resources - which is rarely the case):
public void Dispose() {
IDisposable disposable = resolver as IDisposable;
if (disposable != null) {
disposable.Dispose();
}
resolver = null;
}
See Minimal IDispose implementation for details.
It is optional as the resolver will be correctly disposed with out it - i.e only necessary in the case when you particularly need to control yourself the release of the resources managed by the resovler (what?).

Related

Factory that creates IDisposable objects, how to dispose them?

My application creates IDisposable objects that should be reused, so I create a factory that encapsulates the creation and reuse of those objects, code like this:
public class ServiceClientFactory
{
private static readonly object SyncRoot = new object();
private static readonly Dictionary<string, ServiceClient> Clients = new Dictionary<string, ServiceClient>(StringComparer.OrdinalIgnoreCase);
public static ServiceClient CreateServiceClient(string host)
{
lock(SyncRoot)
{
if (Clients.ContainsKey(host) == false)
{
Clients[host] = new ServiceClient(host);
}
return Clients[host];
}
}
}
public class QueryExecutor
{
private readonly ServiceClient serviceClient;
public QueryExecutor(string host)
{
this.serviceClient = ServiceClientFactory.CreateServiceClient(host);
}
public IDataReader ExecuteQuery(string query)
{
this.serviceClient.Query(query, ...);
}
}
What makes me scratch my head is, ServiceClient is IDisposable, I should dispose them explicitly sometime.
One way is implementing IDisposable in QueryExecutor and dispose ServiceClient when QueryExecutor is disposed, but in this way, (1) when disposing ServiceClient, also needs to notify ServiceClientFactory, (2) cannot reuse ServiceClient instance.
So I think it would be much easier to let ServiceClientFactory manage lifetime of all ServiceClient instances, if I go this way, what is the best practice here to dispose all IDisposable objects created by factory? Hook the AppDomain exit event and manually call Dispose() on every ServiceClient instance?
A couple of things to think about here...
Firstly, what you appear to be describing is some variation of the Flyweight pattern. You have an expensive object, ServiceClient, which you want to reuse, but you want to allow consumer objects to create and destroy at will without breaking the expensive object. Flyweight traditionally does this with reference-counting, which might be a bit old hat.
You'll need to make sure that consumers cannot dispose the ServiceClient directly, so you'll also need a lightweight Facade which intercepts the calls to ServiceClient.Dispose and chooses whether to dispose the real object or not. You should hide the real ServiceClient from consumers.
If all that is feasible, you could rewrite your approach as something like:
// this is the facade that you will work from, instead of ServiceClient
public interface IMyServiceClient : IDisposable
{
void Query(string query);
}
// This is your factory, reworked to provide flyweight instances
// of IMyServiceClient, instead of the real ServiceClient
public class ServiceClientFactory : IDisposable
{
// This is the concrete implementation of IMyServiceClient
// that the factory will create and you can pass around; it
// provides both the reference count and facade implementation
// and is nested inside the factory to indicate that consumers
// should not alter these (and cannot without reflecting on
// non-publics)
private class CachedServiceClient : IMyServiceClient
{
internal ServiceClient _realServiceClient;
internal int _referenceCount;
#region Facade wrapper methods around real ServiceClient ones
void IMyServiceClient.Query(string query)
{
_realServiceClient.Query(query);
}
#endregion
#region IDisposable for the client facade
private bool _isClientDisposed = false;
protected virtual void Dispose(bool disposing)
{
if (!_isClientDisposed)
{
if (Interlocked.Decrement(ref _referenceCount) == 0)
{
// if there are no more references, we really
// dispose the real object
using (_realServiceClient) { /*NOOP*/ }
}
_isClientDisposed = true;
}
}
~CachedServiceClient() { Dispose(false); }
void IDisposable.Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
}
// The object cache; note that it is not static
private readonly ConcurrentDictionary<string, CachedServiceClient> _cache
= new ConcurrentDictionary<string, CachedServiceClient>();
// The method which allows consumers to create the client; note
// that it returns the facade interface, rather than the concrete
// class, so as to hide the implementation details
public IMyServiceClient CreateServiceClient(string host)
{
var cached = _cache.GetOrAdd(
host,
k => new CachedServiceClient()
);
if (Interlocked.Increment(ref cached._referenceCount) == 1)
{
cached._realServiceClient = new ServiceClient(host);
}
return cached;
}
#region IDisposable for the factory (will forcibly clean up all cached items)
private bool _isFactoryDisposed = false;
protected virtual void Dispose(bool disposing)
{
if (!_isFactoryDisposed)
{
Debug.WriteLine($"ServiceClientFactory #{GetHashCode()} disposing cache");
if (disposing)
{
foreach (var element in _cache)
{
element.Value._referenceCount = 0;
using (element.Value._realServiceClient) { }
}
}
_cache.Clear();
_isFactoryDisposed = true;
}
}
~ServiceClientFactory() { Dispose(false); }
void IDisposable.Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
}
// This is just an example `ServiceClient` which uses the default
// implementation of GetHashCode to "prove" that new objects aren't
// created unnecessarily; note it does not implement `IMyServiceClient`
public class ServiceClient : IDisposable
{
private readonly string _host;
public ServiceClient(string host)
{
_host = host;
Debug.WriteLine($"ServiceClient #{GetHashCode()} was created for {_host}");
}
public void Query(string query)
{
Debug.WriteLine($"ServiceClient #{GetHashCode()} asked '{query}' to {_host}");
}
public void Dispose()
{
Debug.WriteLine($"ServiceClient #{GetHashCode()} for {_host} was disposed");
GC.SuppressFinalize(this);
}
}
Secondly, in general, I'd remove the static clauses from the factory and make ServiceClientFactory : IDisposable. You'll see I've done that in my example above.
It may seem like you're just pushing the problem up the chain, but doing so allows you to make this decision on a case-by-case basis, per-something (application, session, request, unit test run -- whatever makes sense) and have the object that represents your something be responsible for the disposal.
If your application would benefit from a single-instance cache then expose a singleton instance as part of an AppContext class (for example) and call AppContext.DefaultServiceClientFactory.Dispose() in your clean-shutdown routine.
The emphasis here is on a clean shutdown. As others have stated, there is no guarantee that your Dispose method will ever actually be called (think power-cycling the machine, mid-run). As such, ideally, ServiceClient.Dispose would not have any tangible side-effects (i.e. beyond freeing resources that would be freed naturally if the process terminates or the machine power-cycles).
If ServiceClient.Dispose does have tangible side-effects, then you have identified a risk here, and you should clearly document how to recover your system from an "unclean" shutdown, in an accompanying user manual.
Thirdly, if both ServiceClient and QueryExecutor objects are intended to be reusable, then let the consumer be responsible for both the creation and disposal.
QueryExecutor only really has to be IDisposable in your sample because it can own a ServiceClient (which is also IDisposable). If QueryExecutor didn't actually create the ServiceClient, it wouldn't be responsible for destroying it.
Instead, have the constructor take a ServiceClient parameter (or, using my rewrite, an IMyServiceClient parameter) instead of a string, so the immediate consumer can be responsible for the lifetime of all objects:
using (var client = AppContext.DefaultServiceClientFactory.CreateServiceClient("localhost"))
{
var query = new QueryExecutor(client);
using (var reader = query.ExecuteReader("SELECT * FROM foo"))
{
//...
}
}
PS: Is there any need for consumers to actually directly access ServiceClient or are there any other objects which need a reference to it? If not, perhaps reduce the chain a little and move this stuff directly to QueryExecutor, i.e. using a QueryExecutorFactory to create flyweight QueryExector objects around cached ServiceClient instances, instead.
Static classes are tricky that way. The constructor for a static class is invoked when an instance member is first invoked. The class is destroyed if and when the application domain is destroyed. If the application terminates abruptly (aborts), there's no guarantee a constructor/finalizer would be called.
Your best bet here is to redesign the class to use a singleton pattern. There are ways to work around this issue, but they require strange, dark magic forces that may cost you your soul.
EDIT: As servy points out, a Singleton won't help here. A destructor is a finalizer, and you won't have any guarantee that it will be called (for a wide variety of reasons). If it were me, I'd simply refactor it to an instantiable class that implements IDisposable, and let the caller deal with calling Dispose. Not ideal, I know, but it's the only way to be sure.

Ninject Factory Extension and Dealing with Memory Leak

This question is more of a "how do I do it?", rather than a "what am I doing wrong?". I have a class which is called QueryProcessor that processes queries (think CQRS). That object is injected into my presenters. The QueryProcessor needs to use the kernel to resolve bindings. Injecting the kernel in, either directly or via a factory, is easy. Doing so without causing a memory leak is the trick.
I have verified using a memory profiler that none of my QueryProcessor objects are being garbage collected. The class looks like this:
public sealed class QueryProcessor : IQueryProcessor, IDisposable
{
private readonly IKernelFactory _container;
private bool _disposed;
public QueryProcessor(IKernelFactory container)
{
_container = container;
}
//[DebuggerStepThrough]
public TResult Process<TResult>(IQuery<TResult> query)
{
var handlerType = typeof(IQueryHandler<,>).MakeGenericType(query.GetType(), typeof(TResult));
dynamic handler = _container.RetrieveKernel().Get(handlerType);
return handler.Handle((dynamic)query);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (disposing && !_disposed)
{
// dispose of stuff here
_disposed = true;
}
}
}
public interface IKernelFactory
{
IKernel RetrieveKernel();
}
My composition root is reasonably straightforward. I am using the factory extension of Ninject.
public void OnLoad(IKernel kernel)
{
// Auto-Register all the validators which are stored in the Service assembly.
AssemblyScanner.FindValidatorsInAssembly(_serviceAssembly).ForEach(
result => kernel.Bind(result.InterfaceType, result.ValidatorType)
);
ManualRegistrations(kernel);
kernel.Bind<IKernelFactory>().ToFactory();
AutoRegisterType(kernel, typeof(IQueryHandler<,>));
AutoRegisterType(kernel, typeof(ICommandHandler<>));
}
As mentioned, the injection is working, but it is leaving a memory leak. How am I supposed to get the Ninject kernel resolving stuff in my QueryProcessor without causing the leak?
Thanks
Update - New Problem
I tried to solve this problem by creating a new kernel with a new module, separate from the main kernel of the Composition Root. These sub-kernels would be created and disposed up, with their lifetimes being tied to that of the QueryProcessors. I hooked it up like this in the main module:
kernel.Bind<IQueryProcessor>().ToMethod(ctx => new QueryProcessor(new StandardKernel(new ProcessorModule(_serviceAssembly)))).InTransientScope();
It works fine before the kernel is disposed of for the first time. But after that, I get the following error message:
Error loading Ninject component ICache
No such component has been registered in the kernel's component container.
Suggestions:
1) If you have created a custom subclass for KernelBase, ensure that you have properly
implemented the AddComponents() method.
2) Ensure that you have not removed the component from the container via a call to RemoveAll().
3) Ensure you have not accidentally created more than one kernel.
Damned if I do, damned if I don't ...
Since your application, not the DI container, is creating the instance it is also responsible for disposing the instance. This scenario can be handled by using the Register, Resolve, and Release pattern.
If you inject the kernel, then you have effectively implemented the service locator anti-pattern. This means your application is explicitly dependent on your DI framework.
Rather than injecting the kernel, you should use an abstract factory as mentioned in the post DI Friendly Framework to handle both creating and releasing the handler instances.
public interface IHandlerFactory
{
dynamic Create(Type handlerType);
void Release(dynamic handler);
}
public interface HandlerFactory
{
private readonly Func<Type, dynamic> handlerMethod;
public HandlerFactory(Func<Type, dynamic> handlerMethod)
{
if (handlerMethod == null)
throw new ArgumentNullException("handlerMethod");
this.handlerMethod = handlerMethod;
}
public dynamic Create(Type handlerType)
{
return handlerMethod(handlerType);
}
public void Release(dynamic handler)
{
IDisposable disposable = handler as IDisposable;
if (disposable != null)
{
disposable.Dispose();
}
}
}
Usage
public sealed class QueryProcessor : IQueryProcessor
{
private readonly IHandlerFactory handlerFactory;
public QueryProcessor(IHandlerFactory handlerFactory)
{
if (handlerFactory == null)
throw new ArgumentNullException("handlerFactory");
this.handlerFactory = handlerFactory;
}
//[DebuggerStepThrough]
public TResult Process<TResult>(IQuery<TResult> query)
{
var handlerType = typeof(IQueryHandler<,>).MakeGenericType(query.GetType(), typeof(TResult));
dynamic handler = this.handlerFactory.Create(handlerType);
try
{
return handler.Handle((dynamic)query);
}
finally
{
this.handlerFactory.Release(handler);
}
}
}
Note that if you use this approach, you are not requiring every handler to implement IDisposable, nor does your QueryProcessor unnecessarily need to implement IDisposable.
In your composition root, you just need to implement the handler method and register it as a parameter to your factory.
Func<Type, dynamic> handlerMethod = type => (dynamic)kernel.Resolve(type);
kernel.Bind<IHandlerFactory>().To<HandlerFactory>()
.WithConstructorArgument("handlerMethod", handlerMethod);
Of course, if you are processing your handlers asynchronously you have to keep the instance alive until the end of the request rather than disposing it as soon as the handler.Handle() method returns. If that is the case, I suggest you analyze the source code for WebApi to work out what pattern is used to do that when dealing with the System.Web.Http.ApiController.

Why is ASP.NET Web Api's Dependency Resolver being disposed?

I have a custom IDependencyResolver:
internal class NinjectResolver : IDependencyResolver
{
private IKernel _kernel;
internal NinjectResolver(params ApplicationModule[] modules)
{
_kernel = new StandardKernel(modules);
}
public IDependencyScope BeginScope()
{
return this;
}
public object GetService(Type serviceType)
{
return _kernel.TryGet(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType)
{
return _kernel.GetAll(serviceType);
}
protected void Dispose(bool disposing)
{
if(disposing)
{
if(_kernel != null && !_kernel.IsDisposed)
{
_kernel.Dispose();
_kernel = null;
}
}
}
public void Dispose()
{
Dispose(true);
GC.SuppresFinalize(this);
}
}
I am registering it like this:
public static void RegisterModules(HttpConfiguration configuration, params ApplicationModule[] modules)
{
_resolver = new NinjectResolver(modules);
configuration.DependencyResolver = _resolver;
}
Everything seems to work fine at the beginning. However, after some minutes (see NOTE) my NinjectResolver is disposed, and therefore begins to throw NullPointerException when trying to resolve a type (this is because I am setting _kernel = null in the Dispose method).
A way to solve this is to keep the reference alive and not set it to null when the resolver is disposed. But why should I?
I mean, why is my resolver getting disposed just like that, from one minute to another? Nowhere in my code am I disposing it explicitly, so it must be the Web Api framework doing it for me.
NOTE: Sometimes it takes a couple of minutes, and sometimes just seconds. It's completely random.
The reason that this class is being disposed is because there is a bug in this class. You are using the NinjectResolver both as resolver and as scope and you are returning the NinjectResolver instance as IDependencyScope by returning it from the BeginScope() method. The BeginScope() method is called once per request by the Web API infrastructure and Web API will call IDependencyScope.Dispose() when the request ends. The problem is that you always dispose the kernel when this happens, which means that your kernel will be unusable after the first request.
A quick fix is to just don't dispose the kernel at all. Since this kernel will live for the duration of the complete application, not disposing the kernel is typically not a problem.

Should objects created by an IDisposable that reference their creator dispose of that creator?

I have a class that implements IDisposable according to this pattern because it contains a reference to HttpClient. It looks something like this:
public class CustomServiceClient : IDisposable
{
HttpClient client;
// ...
public ServiceCreatedEntity GetEntity()
{
// ...
}
~CustomServiceClient()
{
this.Dispose(false);
}
private bool disposed = false;
void IDisposable.Dispose()
{
if(!disposed)
{
this.Dispose(true);
GC.SuppressFinalize(this);
disposed = true;
}
}
public void Dispose(bool disposing)
{
if(disposing)
{
// dispose managed resources
client.Dispose();
}
// dispose unmanaged resources - this class has none
}
}
public class ServiceCreatedEntity
{
CustomServiceClient client;
public ServiceCreatedEntity(CustomServiceClient client)
{
this.client = client;
}
// some functions that use client
}
I'm wondering if ServiceCreatedEntity should implement IDisposable and dispose of the CustomServiceClient. I expect that CustomServiceClient will generally have a longer lifetime than ServiceCreatedEntity, and I'm worried that a client will dispose of ServiceCreatedEntity and be confused as to why their CustomServiceClient has been disposed of as well. Any tips would be greatly appreciated!
it's more of a question of what creates what... the creator should (typically) handle the teardown in a request oriented world.
ServiceCreatedEntity should not dispose the client, but if it has a dependency on the client it doesn't hurt to include a IsDisposed property or Disposing event on the client so that ServiceCreatedEntity can verify that the client is not disposed before using it, or just have CustomServiceClient throw an error if being used after disposal.
I'm confused as to why CustomServiceClient has a method that returns ServiceCreatedEntity and yet ServiceCreatedEntity takes CustomServiceClient as a parameter in its constructor.
Generally, if an object is passed in, it should not be disposed in that object. If an object creates an IDisposable it should itself implement IDisposable and dispose of it. For any other circumstances (such as an IoC container, or something fancy), consider the lifespan of the object and when it will be disposed.
Take a look at this question for more information about IDisposable.

Using statement in every function -> convert to class field with proper cleanup?

Basically I have a few functions that look like this:
class MyClass
{
void foo()
{
using (SomeHelper helper = CreateHelper())
{
// Do some stuff with the helper
}
}
void bar()
{
using (SomeHelper helper = CreateHelper())
{
// Do some stuff with the helper
}
}
}
Under the assumption I can use the same resource instead of a different one [instance] in every function is it ok practice in regard to cleanup and such to do this?:
class MyClass
{
SomeHelper helper = CreateHelper();
// ...foo and bar that now just use the class helper....
~MyClass()
{
helper.Dispose();
}
}
No, do not add a destructor (Finalizer).
You can reuse the resource but then your class has to implement IDisposable.
sealed class MyClass : IDisposable
{
SomeHelper helper = CreateHelper();
// ...foo and bar that now just use the class helper....
//~MyClass()
public void Dispose()
{
helper.Dispose();
}
}
And now you have to use MyClass instances in a using block. It self has become a managed resource .
A destructor is of no use, whenever a MyClass instance is being collected the associated helper object will also be in the same collection. But having a destructor still incurs considerable overhead.
The standard pattern for IDisposable uses a virtual void Dispose(bool disposing) method but when making the class sealed you can use the minimalistic implementation above.
In .NET you don't know when (or whether) finalizer is called at all.
Instead, explicitly indicate that your class is to be disposed of by implementing IDisposable:
(This is exactly what SomeHelper does)
class MyClass : IDisposable
{
readonly SomeHelper helper = CreateHelper();
// any method can use helper
public void Dispose()
{
helper.Dispose();
}
}
using(var myObj = new MyClass()) {
// at the end, myObj.Dispose() will trigger helper.Dispose()
}
I used readonly to ensure helper doesn't get re-assigned somewhere else in the class, but this really doesn't matter if you're careful.
You must be extra careful to never set it to null, or your Dispose will throw an exception. If the field is protected, you can check for nullity before calling Dispose on it so you know you're playing safe.
You can share such a resource during the lifetime of your object, in which case it is recommended that you implement IDisposable.
No, it is not. You don't know when the finalized will un. Also, if your resource is managed, it will be disposed of at some point without the finalized.
If you don't want to use using all the time, perhaps ou can use it once around many functions.
You don't need to override the finalizer in your object, which you have shown in your second code sample by ~MyClass().
You will need to implement the IDisposable pattern. You haven't been explicit in your question if you are using managed and unmanaged resources, but here's a quick sample for a managed resource. Stackoverflow has a myriad of examples on this. Reed Copsey also has a good series on it, and you can start here.
class MyClass : IDisposable
{
private bool _Disposed;
private SomeHelper _Helper;
protected virtual void Dispose()
{
this.Dispose(true);
}
public void Dispose(bool disposing)
{
if (_!Disposed && disposing)
{
if (_Helper != null)
_Helper.Dispose();
_Disposed = true;
}
}
}
The convention is that if your class owns an IDisposable object it should also implement IDisposable. So rather than implementing a finalizer your class should implement IDisposable and dipose of the helper there.
One problem with implementing the finalizer is that you have no control over when it's being called. The disposable pattern gives you a more deterministic way of cleaning up resources.

Categories