Inversifyjs: binding overriding

Created on 25 Mar 2016  路  3Comments  路  Source: inversify/InversifyJS

If I try binding twice the same name/class, I get AMBIGUOUS_MATCH errors. What is the rationale behind that behaviour? Why Inversify doesn't allow binding overriding?

Binding overriding could be really useful to achieve Convention over configuration.

To explain better, consider the following example: I want to create a typescript web framework that optionally allows the programmer to specify the http configuration. I would like to provide a default configuration within my framework and leave to the programmer the possibility to provide custom configuration (so overriding the default one).

// in the framework
let defaultHttpConfig: HttpConfig = {
     httpPort: 8080
};

// other module in the framework
@inject("HttpConfig")
class HttpServer{
     // use HttpConfig
}

// other module in the framework
export function bind(kernel: Kernel){
     kernel.bind("HttpConfig").toValue(defaultHttpConfig);
     kernel.bind("HttpServer").to(HttpServer);
}
//  programmer's code could override HttpConfig
let customHttpConfig: HttpConfig = {
     httpPort: 9090
};

kernel.bind("HttpConfig").to(customHttpConfig)

// creates HttpServer with customHttpConfig
let server = kernel.get<HttpServer>("HttpServer");
question

Most helpful comment

We need it for contextual bindings and multi injection. But you can solve your problem using the unbind method:

kernel.unbind("HttpConfig")
kernel.bind("HttpConfig").to(customHttpConfig)

All 3 comments

We need it for contextual bindings and multi injection. But you can solve your problem using the unbind method:

kernel.unbind("HttpConfig")
kernel.bind("HttpConfig").to(customHttpConfig)

Thanks, that solves my problem.
Congrats for this great work!

Thanks!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

remojansen picture remojansen  路  4Comments

matthewjh picture matthewjh  路  3Comments

AlexanderKiriluyk picture AlexanderKiriluyk  路  4Comments

remojansen picture remojansen  路  3Comments

inaiei picture inaiei  路  4Comments