I am working with Active Directory using C#. Instantiating the PrincipalContext object seems to be expensive, so I'd like to store one in a class variable.
When using PrincipalContext as a local variable, I can use the convenient using syntax. When storing an IDisposable object in a static variable, how do I ensure the object is properly disposed of?
The general pattern for this is to implement the IDisposable interface on your class. Take this example:
public class YourClass : IDisposable
{
private OtherDisposableType yourResource;
public YourClass()
{
yourResource = new OtherDisposableType();
}
public void Dispose()
{
yourResource.Dispose();
}
}
This is, at a minimum, what you need to do.
EDIT
My previous version advocated following the finalizer pattern in all cases, which was (correctly) pointed out to be against the framework design guidelines. However, in the event that you're actually dealing with unmanaged resources (for example, you're making direct P/Invoke calls and obtaining a handle that needs to be explicitly freed) it's advisable that you create a finalizer and call Dispose within it to protect against people who consume your code and don't call Dispose:
public class YourClass : IDisposable
{
private OtherDisposableType yourResource;
public YourClass()
{
yourResource = new OtherDisposableType();
}
public void Dispose()
{
yourResource.Dispose();
GC.SuppressFinalize(this);
}
~YourClass()
{
Dispose();
}
}
Look at what the System.ComponentModel namespace does. Basically, the pattern I typically use is to have a collection of subcomponents, which includes everything I own that's not a 'value' - whether or not it implements IDisposable.
Then, when I Dispose() myself, I iterate over this collection and Dispose anything that implements IDisposable.
One advantage of this technique is that if an object I own starts out not being Disposable, but later adds the IDisposable interface, my class will do the right thing without ever having to change.
Also, use of a DI/IoC container can handle much of this for you.
So basically you want to cache an expensive resource. That's a good thing.
Global data (static variables in this case) is not such a good thing, IMHO. Instead, why not make it an instance variable and control the lifetime?
Write your class that handles the AD responsibilities, have it create and use the PrincipalContext, and make it IDisposable as well (using the Dispose Pattern). Extract an interface from it to decouple it and make classes that use it easier to test.
Classes that want to use AD services will take a constructor parameter of your new interface (Dependency Injection or DI). You can either create your class manually in a using block and pass it to the classes or use a DI Container Framework. You can have the framework set the lifetime of the AD object to the lifetime of the container (which may also be IDisposable). See How do you reconcile IDisposable and IoC? and your DI Container documentation for more on this.
Related
Hey so I have a base class coming from a 3rd party dll, which is dependent on a disposable. Context: IDisposable
public class BaseValidator
{
public BaseValidator(Context context) {}
}
We're trying to move away from tying our classes to these dependencies. So we started relying on providers instead
public interface IContextProvider
{
Context Create();
}
I have a new validator that I'm writing which inherits from the BaseValidator, but I would like it to be dependent on the IContextProvider instead. So I'd like to create the context in the inherited constructor, but I would like to dispose of it in the destructor to prevent memory leaks, However I'm not sure if this is possible.
public class EntityValidator: BaseValidator
{
public EntityValidator(IContextProvider provider) : base(provider.Create())
{
}
~EntityValidator()
{
//I'm not how I can dispose the entity I've passed into it.
}
}
My question is, is there a trick I can use to Capture the variable passed into the base?
Note: I know I can make a work around with an external helper class, but I'm interested if anyone knows how to do this in a more savvy way.
If the BaseValidator class does not expose Context in a public manner, your current design would require you use reflection and knowledge of the internal implementation of BaseValidator to dispose of it, which is of course fragile.
I would instead capture the context using an intermediate constructor:
Context _context;
private EntityValidator(Context context) : base(context)
{
_context = context;
}
public EntityValidator(IContextProvider provider) : this(provider.Create())
{
}
Note, disposing via a finalizer (a.k.a. destructor) is not ideal due to constraints it places on the garbage collector. I'd instead have EntityValidator implement IDisposable
Before, in other language like C++, developpers used to rely on destructors to do a lot of cleaning. It was guaranteed by compiler so it was a strong behavior.
Smart pointer was a good pattern that used this behavior (to implement something like very basic but automatic garbage collection system).
Code was elegant but people used it for a lot of other need. With time a lot of code used to happen in destructor making the debug and readability hard.
IDisposable has been made to force developpers to write explicitely the call to Dispose... This is also useful when you want to Dispose internal resource without your object being destructed. For example in some "Close" method of Stream, where the stream is definitively closed but you can still have reference on steam... and use IsOpen property...
So for me you should not try to hide it. If you depends on code that needs to be Disposed, embrace this dependency... or chose another third party library.
You can simply make the class that need to manipulate Disposable object (BaseValidator) IDisposable too and delegate the need to call to the user.
Usually people that write class implementing IDisposable, in open source project, also write destructor (just in case someone forgot to call Dispose) This is true for a lot of class of .Net framework too (for example Pen() { where nobody thinks to call Dispose on it in some Control drawing events...)
So I would recommend :
Go get the information about if they did it with their classes, if yes they are strong probability they will keep this behavior/code forever. So you can just make your class to inherit IDisposable too, call context.Dispose in your own Dispose implement and that's enough... no need to worry because if your user forgot to call Dispose, the third party do the cleaning. Add a destructor/finalizer on your class only if you have other unmanaged resource to clean too...
Now if they did not, you can just wrap third party "Context" class in your own Context class. Your Context class will have to implement destructor that call Dispose on the instance of third party Context class. And that's it. You can even make your Context class sealed. Your Context class is here to make the behavior of your app as close as if 1) was true and implemented by third party. So this class will be easy to remove later because third party will probably implement finalizer one day (if they are serious). Doing just a sealed wrapper around just one class will avoid some complexity/issue related to how destructors (finallizers) works in .Net : They are all called in any order. Because of this underterministic behavior it makes your code hard to maintain later. For example if third party Context class's finalizer is called before your wrapping class => exception can occured and at a bad time (when gc is doing its stuff) which can make your app crash. Because of all these problems, you better go back to 1)
According to MSDN the best way to implement the IDisposable interface involves using an instance of the SafeHandle class.
In the given example they have the following line;
SafeHandle handle = new SafeFileHandle(IntPtr.Zero, true);
I have been reading about dependency injection and TDD and my understanding is that in order to both follow TDD and implement the IDisposable interface correctly I would have do something like this;
public class SomeDisposableClass : IDisposable
{
private readonly Stream _stream;
private readonly IDisposable _safeHandle;
public SomeDisposableClass(Stream stream, IDisposable safeHandle)
{
_stream = stream;
_safeHandle = safeHandle;
}
private bool disposed = false;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposed) return;
if (disposing)
{
_safeHandle.Dispose();
_stream.Dispose();
}
disposed = true;
}
}
I am injecting my safeHandle instead of instantiating it within SomeDisposableClass. This would allow me to pass in a mock and assert that its Dispose method is called in the event that a SomeDisposableClass instance has its Dispose() method called.
Is this the correct thing to do when using TDD and Dependency injection or am I taking things too far? (i.e. is it OK to instantiate certain classes rather than injecting them or should I avoid "new" like the plague?)
I am aware that there are problems with my example (for example you are not obliged to pass in a SafeHandle instance, only an IDisposable instance).
You shouldn't use DI to provide a SafeHandle to your class. The SafeHandle is an internal implementation detail in your class, that it uses to implement IDisposable. Users of your class shouldn't have to know about this internal implementation. DI is intended to provide your class with external entities that your class collaborates with. Don't be afraid to use new for objects that are used only within your class.
A really good resource is the book: http://www.growing-object-oriented-software.com/ I can't describe the whole book here but here's a couple of ideas. They talk about "values" and "objects".
Values are immutable instances that model fixed quantities. Objects
... use mutable state to model their behavior over time.
The style described in this book uses DI to connect a web of "objects" that collaborate with each other and uses mock objects to test these collaborations. On the other hand, "values" are created with new when needed in both production and test code and passed as parameters and return values.
I am refactoring a program right now. Trying to prevent memory leaks I was looking for objects to enclose in using blocks when I found a TaskDefinition object (class found in Microsoft.Win32.TaskScheduler) that Dispose was not called on. When I tried to enclose it VisualStudio told me that this class does not implement IDisosable. Looking at the class this is certainly true:
namespace Microsoft.Win32.TaskScheduler
{
// Summary:
// Defines all the components of a task, such as the task settings, triggers,
// actions, and registration information.
public sealed class TaskDefinition
{
...
// Summary:
// Releases all resources used by this class.
public void Dispose();
}
}
So why would you implement a Dispose method but not implement the IDisposable interface? Are there any drawbacks from implementing the interface?
Thank you for helping me to understand this.
From the comments:
According to this page, this is a bug that's fixed in newer versions of the assembly.
An additional note, however: the documentation for IDisposable.Dispose explicitly requires implementations to support calling Dispose multiple times, so a valid reason in other cases could be that the class does not support that. In that case, pretending to implement IDisposable but not meeting its requirements would be worse than not implementing it.
I know that similar question was asked several times (for example: here, here,here and here) but it was for previous versions of Unity where the answer was dependent on used LifetimeManager class.
Documentation says:
Unity uses specific types that inherit
from the LifetimeManager base class
(collectively referred to as lifetime
managers) to control how it stores
references to object instances and how
the container disposes of these
instances.
Ok, sounds good so I decided to check implementation of build in lifetime managers. My conclusion:
TransientLifetimeManager - no handling of disposing. Container only resolves instance and it does not track it. Calling code is responsible for disposing instance.
ContainerControlledLifetimeManager - disposes instance when lifetime manager is disposed (= when container is disposed). Provides singleton instance shared among all containers in hiearchy.
HierarchicalLifetimeManager - derives behavior from ContainerControlledLifetimeManager. It provides "singleton" instance per container in hiearchy (subcontainers).
ExternallyControlledLifetimeManager - no handling of disposing. Correct behavior because container is not owner of the instance.
PerResolveLifetimeManager - no handling of disposing. It is generally same as TransientLifetimeManager but it allows reusing instance for dependency injection when resolving whole object graph.
PerThreadLifetimeManager - no handling of disposing as also described in MSDN. Who is responsible for disposing?
Implementation of build-in PerThreadLifetimeManager is:
public class PerThreadLifetimeManager : LifetimeManager
{
private readonly Guid key = Guid.NewGuid();
[ThreadStatic]
private static Dictionary<Guid, object> values;
private static void EnsureValues()
{
if (values == null)
{
values = new Dictionary<Guid, object>();
}
}
public override object GetValue()
{
object result;
EnsureValues();
values.TryGetValue(this.key, out result);
return result;
}
public override void RemoveValue()
{ }
public override void SetValue(object newValue)
{
EnsureValues();
values[this.key] = newValue;
}
}
So disposing container does not dispose disposable instances created with this lifetime manager. Thread completion will also not dispose those instances. So who is responsible for releasing instances?
I tried to manually dispose resolved instance in code and I found another problem. I can't teardown the instnace. RemoveValue of lifetime manager is empty - once the instance is created it is not possible to remove it from thread static dictionary (I'm also suspicious that TearDown method does nothing). So if you call Resolve after disposing the instance you will get disposed instance. I think this can be quite big problem when using this lifetime manager with threads from thread pool.
How to correctly use this lifetime manager?
Moreover this implementation is often reused in custom lifetime managers like PerCallContext, PerHttpRequest, PerAspNetSession, PerWcfCall, etc. Only thread static dictionary is replaced with some other construct.
Also do I understand it correctly that handling disposable objects is dependent on lifetime manager? So the application code is dependent on used lifetime manager.
I read that in other IoC containers dealing with temporary disposable objects is handled by subcontainers but I didn't find example for Unity - it could be probably handled with local scoped subcontainer and HiearchicalLifetimeManager but I'm not sure how to do it.
There are only a few circumstances where Unity will dispose an instance. It is really unsupported. My solution was a custom extension to achieve this - http://www.neovolve.com/2010/06/18/unity-extension-for-disposing-build-trees-on-teardown/
Looking at the Unity 2.0 source code, it smells like the LifetimeManagers are used to keep objects in scope in different ways so the garbage collector doesn't get rid of them. For example, with the PerThreadLifetimeManager, it will use the ThreadStatic to hold a reference on each object with that particular thread's lifetime. However, it won't call Dispose until the container is Disposed.
There is a LifetimeContainer object that is used to hold onto all the instances that are created, then is Disposed when the UnityContainer is Disposed (which, in turn, Disposes all the IDisposables in there in reverse chronological order).
EDIT: upon closer inspection, the LifetimeContainer only contains LifetimeManagers (hence the name "Lifetime"Container). So when it is Disposed, it only disposes the lifetime managers. (and we face the problem that is discussed already).
I came across this issue recently myself as I was instrumenting Unity into my application. The solutions I found here on Stack Overflow and elsewhere online didn't seem to address the issue in a satisfactory way, in my opinion.
When not using Unity, IDisposable instances have a well-understood usage pattern:
Within a scope smaller than a function, put them in a using block to get disposal "for free".
When created for an instance member of a class, implement IDisposable in the class and put clean-up in Dispose().
When passed into a class's constructor, do nothing as the IDisposable instance is owned somewhere else.
Unity confuses things because when dependency injection is done properly, case #2 above goes away. All dependencies should be injected, which means essentially no classes will have ownership of the IDisposable instances being created. However, neither does it provide a way to "get at" the IDisposables that were created during a Resolve() call, so it seems that using blocks can't be used. What option is left?
My conclusion is that the Resolve() interface is essentially wrong. Returning only the requested type and leaking objects that need special handling like IDisposable can't be correct.
In response, I wrote the IDisposableTrackingExtension extension for Unity, which tracks IDisposable instances created during a type resolution, and returns a disposable wrapper object containing an instance of the requested type and all of the IDisposable dependencies from the object graph.
With this extension, type resolution looks like this (shown here using a factory, as your business classes should never take IUnityContainer as a
dependency):
public class SomeTypeFactory
{
// ... take IUnityContainer as a dependency and save it
IDependencyDisposer< SomeType > Create()
{
return this.unity.ResolveForDisposal< SomeType >();
}
}
public class BusinessClass
{
// ... take SomeTypeFactory as a dependency and save it
public void AfunctionThatCreatesSomeTypeDynamically()
{
using ( var wrapper = this.someTypeFactory.Create() )
{
SomeType subject = wrapper.Subject;
// ... do stuff
}
}
}
This reconciles IDisposable usage patterns #1 and #3 from above. Normal classes use dependency injection; they don't own injected IDisposables, so they don't dispose of them. Classes that perform type resolution (through factories) because they need dynamically created objects, those classes are the owners, and this extension provides the facility for managing disposal scopes.
would it be a viable solution to use the HttpContext.Current.ApplicationInstance.EndRequest event to hook to the end of the request and then disposing of the object stored in this lifetime manager? like so:
public HttpContextLifetimeManager()
{
HttpContext.Current.ApplicationInstance.EndRequest += (sender, e) => {
Dispose();
};
}
public override void RemoveValue()
{
var value = GetValue();
IDisposable disposableValue = value as IDisposable;
if (disposableValue != null) {
disposableValue.Dispose();
}
HttpContext.Current.Items.Remove(ItemName);
}
public void Dispose()
{
RemoveValue();
}
you don't have to use a child container like the other solution and the code used to dispose the objects is still in the lifetime manager like it should.
There is a IDisposable which contains a field for the Logger:
class DoesNotDisposeMember : IDisposable {
public IDisposable Logger { get; set; }
public void Dispose ()
{
logger = null;
}
}
Gendarme reports that there is a DisposableFieldsShouldBeDisposedRule-Defect, but I don't want to dispose the logger.
Can anyone help me?
Setting side why you wouldn't want to dispose of it; if you don't want to dispose of it, you probably should not be storing it in an IDisposable member, then. The only real purpose of that interface is to signify/enable that item being disposed.
If it's a logging object, is there not another common base interface/class you can use, such as one derived from Stream or StreamWriter?
Now that I've written that, it of course strikes me that this still includes IDisposable in the hierarchy... which I suppose brings us back to what I said I would set aside:
Why are you setting a variable here that you do not intend to dispose of? If you are disposing of it elsewhere, you should probably also use it there. The code that is wrapping the logger object should handle all the functionality of it, including exposing the separate interface to your model/business objects that enables logging.
Basically, if you are encapsulating the logging in another object, then you should not be referencing the internal logging stream object outside of that object. If you aren't encapsulating logging elsewhere, then this class should dispose of it appropriately.