tsframework / ts-framework

A Web Framework for Nodejs
http://tsframework.github.io
MIT License
43 stars 6 forks source link

Proposal: Integrate using a typescript compatible Dependency Injector #27

Closed atrakeur closed 8 years ago

atrakeur commented 8 years ago

Using Dependency Injection is a common pattern in maintainable application. Basicaly, when a component require other components to operate, it's the application's responsibility to provide them.

Due to the typed nature of typescript, there are several Injection Container available out there than can work (almost automaticaly).

I propose to integrate one so that every component of the framework is loosely coupled.

For example the router can see his controllers be injected automaticaly. Then each controller can have an instance of a Repository injected. Then in turn each Repository get an instance of the Database (possibly a single shared instance?) and finally the database get an instance to his database drive.

The container must be decorator based, Easy to use and understand, and also not too much intrusive (I mean user code can run possibly without it)

Possible candidates are:

Feel free to comment on that matter.

atrakeur commented 8 years ago

Okay so here is my proposal on that matter.

From now on, let's see the Framework as a bunch of independent components. For example we got a Database component, and an http server component.

Each component are dependent only with the dependency injection container and a bunch of interfaces. This way, all components are loosely coupled (work independently and replaceables as long as you provide another component that follow the same interface).

Each component define a special class called a service provider (HttpServiceProvider). This class is responsible to register every service the component provides to the injection container. With my proff of concept implementation, it goes along the lines of:

container.register("Configuration", new configuration);

The user, at the start of the application, defines which services providers to load. For example a given application may need HttpServiceProvider, ModelProvider, but don't need AuthProvider.

Of course there is specials services providers for Controllers and Models (ie, they look some predefined locations and look for @Controller or @Model anotation).

With this architecture, it's easy to write an additionnal libraries for the framework: write down your code, write down your service provider to bind code to the framework, ask your users to npm install and add the service provider to their list of providers. No more manual requiring, no more long installation instructions, and no more crazy loading code lying across the whole application.

The good sides are:

The bad sides:

A PR with an example implementation (just the Router and Config components) is on his way.