Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.