Skip to content

Binding Decorators #926

@chrisbanes

Description

@chrisbanes

Description

We had this feature in our custom DI framework at Twitter, and it was super handy for large codebases.

Here's the use case that I'm thinking, but I'm 100% sure that there's more. We have a Logger with takes a tag, and in every class we either:

  • Create a copy of the logger: val classLogger = logger.withTag("MyClassName")
  • Or just pass it in at the calls logger.d(TAG)

It would be nice if we could attach some kind of decorator so that the injected logger is pre-decorated with the class name as tag.

The API could be something like the following:

annotation class BindingDecorator(val type: KClass<Any>)

interface Decorator<T> {
  fun decorate(context: BindingContext, value: T): T
}

Then to create and attach a decorator:

annotation class LoggerDecoration

@Inject
@BindingDecorator(LoggerDecoration::class)
class LoggerDecorator : Decorator<Logger> {
  override fun decorate(context: BindingContext, source: Logger): Logger {
    return logger.withTag(context.callee.simpleName)
  }
}

Then, every Logger injected into a class would be automatically decorated with the class name.

This is just one example. Others could include:

  • Tracing. A tracing decorator which automatics add Trace sections around binding functions
  • I'll think of more 😄

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions