Dependency Injection
Learn how RuneLite automatically provides objects to your plugin.
Dependency Injection (DI) is a pattern where objects are provided to your code automatically, rather than you creating them yourself.
How It Works in RuneLite
When you use @Inject, RuneLite's DI system:
1. Looks at what you need (e.g., Client)
2. Creates or finds an instance
3. Provides it to your plugin automatically
Why Use DI?
- **No manual creation**: RuneLite handles object creation
- **Shared instances**: Multiple plugins can share the same Client
- **Lifecycle management**: RuneLite manages when objects are created/destroyed
- **Testing**: Easy to provide mock objects for testing
What Can Be Injected?
Common injectable objects:
- **Client**: Access to game state
- **OverlayManager**: For managing overlays
- **MenuManager**: For modifying menus
- **ItemManager**: For item prices and definitions
- **ConfigManager**: For accessing configs
- **Your Config**: Your plugin's config interface
Example
public class MyPlugin extends Plugin {
@Inject
private Client client; // RuneLite provides this
@Inject
private OverlayManager overlayManager; // RuneLite provides this
// No need to create these yourself!
// Note: EventBus is no longer needed - @Subscribe is auto-registered
}
Best Practices
- Use @Inject for all RuneLite services
- Don't try to create Client or other RuneLite objects manually
- Inject in fields, not in methods
- RuneLite handles the lifecycle automatically
Code Examples
Example 1
1// Injecting dependencies
2public class MyPlugin extends Plugin {
3 @Inject
4 private Client client;
5
6 @Inject
7 private OverlayManager overlayManager;
8
9 @Inject
10 private MenuManager menuManager;
11
12 @Inject
13 private MyPluginConfig config;
14
15 // All of these are provided by RuneLite automatically!
16 // No need to create them yourself
17 // Note: EventBus is no longer needed - @Subscribe is auto-registered
18}Example 2
1// Using injected objects
2@Subscribe
3public void onGameTick(GameTick event) {
4 // Use the injected Client
5 Player player = client.getLocalPlayer();
6
7 // Use the injected config
8 if (config.enabled()) {
9 // Do something
10 }
11}