简体   繁体   中英

Aurelia DI configuration class a la Spring @configuration

I'm trying to figure out how to create a configuration class similar to what you would do with spring in Aurelia. The use case is to basically have consumed modules that provide functionality such as persistence to manage their own configuration (creating connections, registering dependencies, etc...).

In spring, you can have something like this (pseudocode, hasn't been tested):

@Configuration
class Config {
    @Bean
    public Connection createConnection(string cnt) {
      // TODO: create connection
    }
}

The above code would execute the createConnection method and register a connection with the container, and also pass the cnt connection string variable when calling the method.

I believe I can do something like the following:

export class Dependencies {
    public configure(container: Container): void {
        let cnt: string = container.get('cnt');
        container.registerSingleton(Connection, () => {
           // TODO: create connection
        })
    }
}

And then call this somewhere else like so:

class App {
   constructor(dependencies: Dependencies) {
       dependencies.configure(this.container, this.cnt);
   }
}

The problem with this approach, is that configuration becomes explicit, and you have to know what the configuring class is named, what methods to call, as well as when to call it, since you want your connection string to be registered before creating a connection.

IMHO, having an explicit configuration step makes thing less tightly coupled. Also, having a way of providing dependencies by way of a factory method also makes configuration easier and more 'ergonomic'.

In summary, my two questions are:

  1. Is it possible to have an explicit configuration @configuration step, like @singleton or @transient ?
  2. How do I register dependencies through a factory method/function, preferably using a decorator?

aurelia-dependency-injection模块不支持该用例,但是现在有一个模块对此添加了支持-aurelia-factory-methods

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM