Search code examples
c#classidisposable

Implementing IDisposable on Class with Generic Type Where Generic Type Is Disposable


I have a generic ServiceResult<T> class that I use in my service layer to provide a generic return type wrapped in basic information to support the addition of Errors, and whether the call succeeded or not, etc.

In working through my services, I now have an email service which currently returns a MailMessage which implements the IDisposable interface. I am not quite sure how to structure my class to handle this because I would ultimately like to wrap my service call in a using statement to ensure the generic type is disposed of properly but the current way I'm laying out the disposable implementation isn't quite cutting it. Would this be as simple as adding an additional clause to have the class itself implement IDisposable even if there is nothing to dispose for the wrapper class itself?

DisposableServiceResult Class:

public class DisposableServiceResult<T> where T : IDisposable
{
    private List<string> Errors { get; } = new List<string>();
    private T _result;
    public T Result { get { return _result; } }

    // Other various properties and and methods

    public void Dispose()
    {
        _result.Dispose();
    }
}

Service Call:

using (var emailBuildResult = await services.emailBuilder.BuildEmailFromEntityAsync(client, "TemplateName", "myemail@email.com"))
{
    // do stuff here
}

Solution

  • The class should be declared as

    public class DisposableServiceResult<T> : IDisposable where T : IDisposable