Typescipt Dependency Injection

Full working code examples are available on githubSometimes our classes rely on other services or values that need to be initialized on own...

Reading Time
6 min (~1068 words)
Tags
Typescript
Date
7/7/2019
Typescipt Dependency Injection

Full working code examples are available on github

Sometimes our classes rely on other services or values that need to be initialized on their own before our class interacts with it, or we want to use a mock implementation of a service or value for testing purposes. A common solution to this problem is dependency injection through a factory. (Sometimes called IOC or Inversion of Control). Today, I'll show you how to use typescript decorators along with a lazy factory to inject dependencies into your classes at runtime. This makes it easy to test your code and have precise control over runtime dependencies without having to spread that logic out across many different places.

To start things off, lets make sure our tsconfig.json is set up and ready to work with decorators by enabling two optional flags:

1...
2"experimentalDecorators": true,
3"emitDecoratorMetadata": true,
4...

Now in our source code we can set up a lazy factory. This class will be responsible for creating instances of whatever we want and can be as flexible as we need! We'll use the singleton pattern to ensure there's only ever one instance of the factory at a time to avoid duplication.

di/LazyFactory.ts

1export class LazyFactory {
2
3    // this is where we store our singleton reference to this class instance
4    private static instance: LazyFactory;
5
6    // hide constructor, must use getInstance
7    private constructor() {}
8
9    // if there is not yet an instance of this class, create it. Otherwise return that instance
10    public static getInstance() {
11        if (!LazyFactory.instance) {
12            LazyFactory.instance = new LazyFactory();
13        }
14        return LazyFactory.instance;
15    }
16}

That's all we need to get rolling! now we can add methods to the LazyFactory to return whatever we need at runtime. Let's add one now to return an instance of MyService. One of the benefits of our lazy factory is we can easily swap out implementations of what it returns for mocking purposes. We'll use an interface to define MyService's public methods and fields, then we can implement that interface with a mock and real implementation. Our LazyFactory can then determine which version of the service to give us dynamically!

First we'll define the IMyservice interface like so:

services/IMyService.ts

1export interface IMyService {
2    sayHello(name: string): void;
3}

Now we can define a mock and real implementation of the service using this interface:

services/MyService.ts

1export class MyService implements IMyService {
2    public sayHello(name: string): void {
3       console.log(`Hello from the real service, ${name}!`);
4    }
5}

services/MockMyService.ts

1export class MockMyService implements IMyService {
2    public sayHello(name: string): void {
3        console.log(`Hello from the mock service, ${name}!`);
4    }
5}

Back in our LazyFactory we can create a method to return the correct implementation of IMyService - in this case I'll use the current environment to determine which instance to return:

di/LazyFactory.ts

1export class LazyFactory {
2    ...
3    public myService() {
4        if (process.env.ENV === 'production') {
5            return new (require('../service/MyService')).MyService();
6        }
7        return new (require('../service/MockMyService')).MockMyService();
8    }
9}

NOTE: You might be wondering why we're using this odd require syntax - it's not always necessary but I've seen some strange behaviour pop up when using this factory with some webpack configurations. it might not be necessary but your mileage may vary!

Phew! That's a lot - but we're almost done! The last thing we need to do is actually use our LazyFactory!

for this example, we'll be working in app.ts which has need of our MyService:

app.ts

1import {LazyFactory} from './LazyFactory';
2
3class App {
4    private myService: IMyService;
5
6    constructor() {
7        this.myService = LazyFactory.getInstance().myService();
8    }
9
10    public main() {
11        this.myService.sayHello('internet');
12    }
13}
14
15new App().main();

and we're done! LazyFactory will look up the correct version of our MyService and return it. This makes testing code in isolation much easier to do since you can keep the mock versions of your services dumb.

You might be wondering about those decorator options we set up earlier, and I've not forgotten that - I just wanted to illustrate that this is completely possible to achieve without using decorators.

Now we'll define an @Inject typescript decorator that will handle the construction and assignment in App for us!

The code for @Inject looks like this:

decorators/Inject.ts

1import {LazyFactory} from '../di/LazyFactory';
2
3export const Inject = (target: any, key: string) => {
4    let val = target[key]
5
6    if (delete target[key]) {
7        Object.defineProperty(target, key, {
8            get: () => {
9                // an ugly cast :(
10                // if you know a good way to do this without converting LazyFactory to an object literal please let me know!
11                const concrete = (LazyFactory.getInstance() as any)[key];
12                if (concrete) {
13                    val = concrete();
14                }
15                return val;
16            },
17            enumerable: true,
18            configurable: true
19        });
20    }
21};

What this does is look for key in target - target will be whatever class we use the @Inject decorator in. if it finds that key in target and our LazyFactory has a matching key, it will replace key with the match found in the LazyFactory. Sounds like a lot, but It's fairly simple, let's write some code that uses this decorator to get a better understanding of what's going on.

back in app.ts:

1import {Inject} from './Inject';
2
3class App { // <-- App will be the `target` referenced in the Inject function
4    @Inject
5    private myService!: IMyService; // <-- this field `myService` will be the key
6
7    constructor() { /*...this is empty now! */ }
8
9    public main() {
10        this.myService.sayHello('internet');
11    }
12}
13
14new App().main();

We can now add as many other services to our LazyFactory as we want, and @Inject them! As long as the method name in LazyFactory matches the field name where it's being injected it will work no problem.

But wait! There's more!

LazyFactory doesn't actually care what we return from any method - this is super useful because it lets us swap out any kind of data we want. I've used it to return a baseURL that differs locally vs in production:

1export class LazyFactory {
2    ...
3    public baseURL() {
4        if (process.env.ENV === 'production') {
5            return 'https://prod.myAPI.com';
6        }
7        return 'https://stage.myAPI.com';
8    }
9}

now back in MyService and MockMyService we can inject this baseURL as well!

services/MyService.ts

1export class MyService implements IMyService {
2
3    @Inject
4    private baseURL: string; // <-- 'https://prod.myAPI.com'
5
6    public sayHello(name: string): void {
7        console.log(`Hello from the real service, ${name}!`);
8        console.log('baseURL is ', this.baseURL);
9    }
10}

services/MockMyService.ts

1export class MockMyService implements IMyService {
2
3    @Inject
4    private baseURL: string; // <-- 'https://stage.myAPI.com'
5
6    public sayHello(name: string): void {
7        console.log(`Hello from the mock service, ${name}!`);
8        console.log('baseURL is ', this.baseURL);
9    }
10}

Full working code examples are available on github

I hope this has been a useful explanation of some of the benefits of dependency injection. While this method is not perfect, it is very flexible and lets you fine tune its behaviour as much as you want/need.