# Dependency injection

When using lifecycle methods (`canActivate`, `canDeactivate`), middleware or plugins, you might need to access specific objects from your application: a store, a specific API, etc... You can pass their reference to router5 and they will be passed alongside your router instance.

For TypeScript users, `createRouter` accepts a generic for typing dependencies.

You can register all dependencies at once, or one by one.

```javascript
const router = createRouter(routes, options, dependencies)
```

```javascript
router.setDependencies({ store, api })
// or
router.setDependency('store', store)
router.setDependency('api', api)
```

You can retrieve your current dependencies references using `getDependencies()`.

Lifecycle methods (`canActivate`, `canDeactivate`), middleware or plugins will be called with them:

```javascript
const plugin = (router, dependencies) => ({
    /*
        onStart() {},
        onStop() {},
        onTransitionStart() {},
        ...
    */
})
```

```javascript
const canActivate = (router, dependencies) =>
    (toState, fromState, done) {
        /* ... */
    }
```

```javascript
const middleware = (router, dependencies) =>
    (toState, fromState, done) {
        /* ... */
    }
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://router5.js.org/advanced/dependency-injection.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
