auto-node
Dependency injection module inspired by C#'s Autofac
Last updated 4 years ago by burkhartt .
ISC · Original npm · Tarball · package.json
$ cnpm install auto-node 
SYNC missed versions from official npm registry.

Autonode

Dependency injection for NodeJS inspired by Autofac (C# DI library)

Getting Started

Installation

npm install auto-node

Setup

let autonode = require('auto-node');

let app = express();
app.use(autonode.Middleware);

app.use((req, res, next) => {
  let containerBuilder = new autonode.ContainerBuilder();
  containerBuilder.registerType('UserRepository', UserRepository, autonode.LifetimeScope.InstancePerRequest);
  autonode.Container.load(containerBuilder);
}

Basic Usage

let container = require('auto-node').Container;

class UserRepository {
  constructor() {
    this.logger = container.resolve('logger');
  }
}

API

Registration

containerBuilder.register(key, instanceFunction, lifetimeScope);
containerBuilder.registerType(key, classType, lifetimeScope);

Lifetime Scopes

autonode.LifetimeScope.InstancePerRequest
autonode.LifetimeScope.SingleInstance
autonode.LifetimeScope.None

Examples

Instance referencing another registration

containerBuilder.register('lineItemRepository', () => new LineItemRepository(), autonode.LifetimeScope.InstancePerRequest);
containerBuilder.register('tripRepository', (c) => new TripRepository(c.resolve('lineItemRepository'), autonode.LifetimeScope.InstancePerRequest);

Automatic constructor injection

containerBuilder.registerType('lineItemRepository', LineItemRepository, autonode.LifetimeScope.InstancePerRequest);
conatienrBuilder.registerType('tripRepository', TripRepository, autonode.LifetimeScope.InstancePerRequest);

class TripRepository {
  constructor(lineItemRepository) { // parameter name must match registration key
    this.lineItemRepository = lineItemRepository;
  }
}

class LineItemRepository {
  constructor() { }
}

Access request from anywhere without passing it to every function

containerBuilder.register('request', () => req);
containerBuilder.register('requestAwareTripRepository', (c) => new TripRepository(c.resolve('request')));

Current Tags

  • 0.0.7                                ...           latest (4 years ago)

4 Versions

  • 0.0.7                                ...           4 years ago
  • 0.0.5                                ...           4 years ago
  • 0.0.4                                ...           4 years ago
  • 0.0.3                                ...           4 years ago
Maintainers (1)
Downloads
Today 0
This Week 0
This Month 1
Last Day 0
Last Week 0
Last Month 2
Dependencies (4)
Dev Dependencies (2)
Dependents (0)
None

Copyright 2014 - 2016 © taobao.org |