-
Notifications
You must be signed in to change notification settings - Fork 298
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fx.Self: a parameter to fx.As for providing a type as itself (#1201)
We frequently see requests for folks who want to use `fx.As` to provide a type as another type, while also providing it as itself. To name a few: * #1196 * #1148 * #1079 This is currently not possible via strictly using `fx.As` + a single constructor, since `fx.As` causes a constructor to no longer provide its original type. The workaround we often give is for folks to do something like this, which involves adding a second "constructor": ```go fx.Provide( newConcreteType, func(ct *concreteType) Interface { return ct } ) ``` which is admittedly not very ergonomic. A somewhat common pattern mistaken to be a workaround is providing the constructor twice instead: ```go fx.Provide( newConcreteType, fx.Annotate(newConcreteType, fx.As(new(Interface))), ) ``` This PR adds `fx.Self()`, which returns a special value to indicate an `fx.As` should retain that original return type: ```go fx.Provide( newConcreteType, fx.As(fx.Self()), fx.As(new(Interface)), ) ``` As an alternative, I considered a new annotation altogether, named something like `fx.AlsoAs`, but adding a special type that can be passed as an argument to `fx.As` directly allows for more fine-tuned control over individual positional return values. For example, this function's return types can be easily expressed as `*asStringer` and `io.Writer` using `fx.Self()`: ```go fx.Provide( fx.Annotate( func() (*asStringer, *bytes.Buffer) {/* ... */ }, fx.As(fx.Self(), new(io.Writer)), // return values will be: *asStringer, io.Writer ), ), ``` Whereas something like `fx.AlsoAs` wouldn't provide the ability to skip over the first positional return value entirely.
- Loading branch information
Showing
2 changed files
with
161 additions
and
10 deletions.
There are no files selected for viewing
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
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