Define an application that wires three components together.
← Dependency Injection · Ref: Q1113
Create the DI registry and connect it to a program:
defines application MyApp register ConsoleLogger() as Logger register GreetingService() as Service
defines program Main() with application of MyApp
'with application of' connects the program to the registry. All injection points resolve from this application.
See Q1110 for register/inject basics. See Q1111 for ordering.
Example
defines module qa.di.applicationregistry defines component Logger as abstract log() as abstract -> message as String <- output as String? default operator ? ConsoleLogger is Logger override log() -> message as String <- output as String: `[LOG] ${message}` default operator ? Formatter as abstract format() as abstract -> text as String <- result as String? default operator ? UpperFormatter is Formatter override format() -> text as String <- result as String: text.upperCase() default operator ? Service as abstract greet() as abstract -> name as String <- greeting as String? default operator ? GreetingService is Service logger as Logger! formatter as Formatter! override greet() -> name as String <- greeting <- String() formatted <- formatter.format(name) greeting: logger.log(formatted) default operator ? defines application GreetApp register ConsoleLogger() as Logger register UpperFormatter() as Formatter register GreetingService() as Service defines program ApplicationRegistryDemo() with application of GreetApp stdout <- Stdout() service as Service! result <- service.greet("World") stdout.println(result)
Common mistakes
E08220 — A program that uses DI injection must be linked to its application with 'with application of AppName' (EK9 has no wiring annotations). See ek9 -h E08220 for details.
Incorrect:
ApplicationRegistryDemo()
Correct:
ApplicationRegistryDemo() with application of GreetApp
Other ways to ask this
- I need an application block that registers Logger, Formatter, and Service
- In Spring I'd use @Configuration with @Bean methods. Write the EK9 application
- Given three components with dependencies, define the application wiring
- Set up a complete application registry with multiple registrations
Coming from another language?
Spring: @SpringBootApplication + @Configuration. Guice: AbstractModule.configure(). .NET: Program.cs with builder.Services. EK9: defines application with register statements.
Keywords: registry, register, wire, DI, application, configuration