-
Notifications
You must be signed in to change notification settings - Fork 1
ToConstructorBindings
Occasionally it's necessary to bind a type to an arbitrary constructor. This comes up when the @Inject annotation cannot be applied to the target constructor: either because it is a third party class, or because multiple constructors that participate in dependency injection. @Provides methods provide the best solution to this problem! By calling your target constructor explicitly, you don't need reflection and its associated pitfalls. But there are limitations of that approach: manually constructed instances do not participate in AOP.
To address this, Salta has toConstructor() bindings. They require you to reflectively select your target constructor:
public class BillingModule extends AbstractModule {
@Override
protected void configure() throws Exception{
bind(TransactionLog.class).toConstructor(
DatabaseTransactionLog.class.getConstructor(DatabaseConnection.class));
}
}In this example, the DatabaseTransactionLog must have a constructor that takes a single DatabaseConnection parameter. That constructor does not need an @Inject annotation. Salta will invoke that constructor to satisfy the binding.
Each toConstructor() binding is scoped independently. If you create multiple singleton bindings that target the same constructor, each binding yields its own instance.
The Salta wiki. It was copied from the Guice Wiki and adapted to Salta.
- Home
- Why Dependency Injection?
- Getting Started
- Bindings
- Scopes
- Injections
- Injecting Providers
- AOP
- Speed
- Frequently Asked Questions
- Extending Salta
- Internals
- Best Practices
- Community