Created
November 12, 2010 00:57
-
-
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).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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