Today I made the switch from a js electron project to typescript and found myself wondering about the equivalent of angular's dependency injection. Since Angular Universal is still in its early stages and lacks documentation on using it with electron instead of express, I decided to explore inversify as a potential solution. It seemed like a good fit for my needs, especially considering its lighter weight compared to angular, as I only require dependency injection.
I started experimenting with creating a decorator that would function similarly to the NgModule
decorator in Angular.
import { app, Menu, ipcMain, BrowserWindow } from 'electron';
import { Container } from 'inversify';
import { DatabaseService } from 'core/database.service';
function servermodule(data: {providers: Array<any>}) {
// Some code that instantiates the declarations array classes
// Do they need to be returned if I don't need a reference?
let container = new Container();
return (target: Object) => {
for(const service of data.providers) {
container.bind(service).toSelf();
}
}
}
This function loops through each entry in providers and binds it to inversify's container object. I plan to use this function as follows, mimicking the usage of angular's decorator.
@servermodule({
declarations: [
// Other classes that may receive DatabaseService injection
],
providers: [
DatabaseService
]
})
export class AppModule { ...
The DatabaseService
class could look something like this:
import { injectable } from 'inversify';
@injectable()
export class DatabaseService { ...
And it should be injectable in an angular-style manner, for example:
import { inject } from 'inversify';
import { DatabaseService } from './database.service';
export class Models {
constructor(@inject(DatabaseService) dbService: DatabaseService) { }
}
I'm uncertain about the scope of inversify's container. Does it only exist within the decorator function? Would it be better to initialize it like this?
container = new Container({ autoBindInjectable: true });
How can I properly return it to the AppModule
? Is my idea of declaring the classes in the servermodule decorator a viable approach?
Currently, I'm encountering the following error message during tsc compilation and electron execution, even though there are no ts linting errors.
App threw an error during load
Error: Cannot find module 'database.service'
Another idea/question I have is: if I want to include an import attribute in addition to declarations and providers, would it be a good practice to modify the constructor with the decorator and import these classes as well?
Thank you!