Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement IDisposable in the Harmony class #43

Closed
ManlyMarco opened this issue Jan 16, 2022 · 2 comments
Closed

Implement IDisposable in the Harmony class #43

ManlyMarco opened this issue Jan 16, 2022 · 2 comments
Labels
enhancement New feature or request

Comments

@ManlyMarco
Copy link
Member

Can be an explicit implementation. All disposing has to do is call UpatchSelf.

This would be useful when working with the disposable pattern, for example when making a plugin that can be hot-reloaded. Currently you have to do this:

var hi = Harmony.CreateAndPatchAll(typeof(Hooks), typeof(Hooks).FullName);
return Disposable.Create(() => hi.UnpatchSelf());

when it could be just this:

return Harmony.CreateAndPatchAll(typeof(Hooks), typeof(Hooks).FullName);

You could use it inside using as well but that's a pretty uncommon case.

Example of the disposable pattern to make a plugin reloadable:

private static readonly List<IDisposable> _cleanupList = new List<IDisposable>();

private void Start()
{
    try
    {
        _cleanupList.Add(RegisterButtons());
        _cleanupList.Add(Hooks.ApplyHooks());
    }
    catch
    {
        OnDestroy();
        throw;
    }
}

private void OnDestroy()
{
    foreach (var disposable in _cleanupList)
    {
        try
        {
            disposable.Dispose();
        }
        catch (Exception ex)
        {
            UnityEngine.Debug.LogException(ex);
        }
    }
}
@ManlyMarco ManlyMarco added the enhancement New feature or request label Jan 16, 2022
@ghorsington
Copy link
Contributor

Sounds good. I added a hidden implementation of Dispose now, check 511a1fa

Or should the Dispose be public? I think it's more reasonable to keep it hidden so that you can still use using and other IDisposable helpers while still encouraging users to use UnpatchSelf for common cases.

@ManlyMarco
Copy link
Member Author

Nice, thanks. I think it should be private for the reason stated.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants