Skip to content

Instantly share code, notes, and snippets.

@thoward
Created November 12, 2010 00:57
Show Gist options
  • Save thoward/673545 to your computer and use it in GitHub Desktop.
Save thoward/673545 to your computer and use it in GitHub Desktop.
An example workaround to add IDisposable support to objects that don't implement it (like Lucene.Net objects).
using System;
using Lucene.Net.Index;
namespace Lucene.Net.Extensions
{
public class Disposable<T> : IDisposable
{
public Disposable() { }
public Disposable(T entity, Action<T> disposeAction)
{
Entity = entity;
DisposeAction = disposeAction;
}
public T Entity { get; set; }
public Action<T> DisposeAction { get; set; }
public void Dispose()
{
if (default(Action<T>) != DisposeAction)
DisposeAction(Entity);
}
}
public static class DisposableExtensions
{
public static Disposable<T> AsDisposable<T>(this T entity, Action<T> disposeAction)
{
return new Disposable<T>(entity, disposeAction);
}
}
public class LuceneDisposableExample
{
public void Example()
{
string pathToIndex = @"C:\lucene\example\index";
using (var disposableReader = IndexReader.Open(pathToIndex, true).AsDisposable(a => a.Close()))
{
var reader = disposableReader.Entity;
// .. whatever you want here...
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment