I suggest that another alternative that you can use is to wrap your instances with a one-time type so that it can automatically handle the type deletion regardless of whether this type is actually a one-time type. For example, I could define something like:
public class DisposableWrapper<T> : IDisposable { private readonly T _instance; private readonly IDisposable _disposable; public DisposableWrapper(T instance) { _instance = instance; _disposable = instance as IDisposable; } public void Dispose() { if (_disposable != null) _disposable.Dispose(); } public static implicit operator T(DisposableWrapper<T> disposableWrapper) { return disposableWrapper._instance; } }
(Hopefully with a slightly bigger mistake!)
Given that I know, in terms of deletion, whether the type is disposable, I can name it accordingly. I can also provide an implicit statement to return to the internal type. With the above and excellent extension method:
public static class DisposableExtensions { public static DisposableWrapper<T> Wrap<T>(this T instance) { return new DisposableWrapper<T>(instance); } }
Suppose I have a service that I injected into a type, it could be:
public interface IUserService { IUser GetUser(); }
I could do something like:
public HomeController(IUserService service) { using (var disposable = service.Wrap()) { var user = service.GetUser();
Now, regardless of whether this particular implementation of IUserService
available or not, I can still safely work on the assumption that it does not matter.
Another quick console example:
class Program { static void Main(string[] args) { using (var instance = new ClassA().Wrap()) { ClassA instanceA = instance; } using (var instance = new ClassB().Wrap()) { ClassB instanceB = instance; } Console.ReadKey(); } } public class ClassA { } public class ClassB : IDisposable { public void Dispose() { Console.Write("Disposed"); } }
source share