Skip to content

Release method #1179

@saturn4er

Description

@saturn4er

Is your feature request related to a problem? Please describe.
Currently, the fx.App lifecycle management allows us to create and start application components seamlessly. However, there's a missing piece in the lifecycle: a clean, explicit way to release resources such as database connections or open files, which are initiated during provider invocation. This becomes particularly necessary in scenarios where the application might not reach the .Start phase, or when only a single job is needed, thus not requiring the full application start-stop cycle. Without an explicit release mechanism, we are forced to implement ad-hoc, potentially error-prone solutions to ensure resources are properly released.

Describe the solution you'd like
I propose the addition of a .Release method to the fx.App structure, alongside a new lifecycle hook: fx.OnRelease. This would allow developers to define clean-up functions that are executed when .Release is called, ensuring that all resources are properly closed or released, regardless of whether the application fully starts or not. This feature could be implemented as follows:

fx.Provide(fx.Annotate(fx.NewMySQLDB, fx.OnRelease(CloseMySQLDB)))

Here, CloseMySQLDB would be a function designed to cleanly shut down the MySQL database connection established by NewMySQLDB, and would be automatically invoked when fx.App.Release is called.

app := fx.New(...)
defer app.Release()

Describe alternatives you've considered
One alternative might be to manually manage resource release outside of the fx lifecycle, by storing references to all resources that need to be released and explicitly calling their release methods. However, this approach can quickly become cumbersome and error-prone, especially in larger applications with many resources to manage.

Another alternative could be to use the existing OnStop hook for releasing resources. However, this is not always viable because OnStop is only called if the application successfully starts, which may not always be the case, especially in applications that perform tasks without entering the full start-stop cycle.

Is this a breaking change?
This proposal should not introduce breaking changes to the existing fx API. The addition of fx.App.Release and fx.OnRelease would be backward compatible, offering additional functionality without altering the current behavior of existing applications using the fx library.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions