本文整理汇总了TypeScript中container-ioc.Container类的典型用法代码示例。如果您正苦于以下问题:TypeScript Container类的具体用法?TypeScript Container怎么用?TypeScript Container使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Container类的4个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。
示例1: Container
import { Container } from 'container-ioc';
/*
If a container can't find a value within itself, it will look it up in ascendant containers.
There a 3 ways to set a parent for a container:
*/
const grandParentContainer = new Container();
// 1.
const parentContainer = grandParentContainer.createChild();
// 2.
const childContainer = new Container();
childContainer.setParent(parentContainer);
// 3.
const deepNestedContainer = new Container({
parent: childContainer
});
grandParentContainer.register([
{ token: 'IConfig', useValue: {}}
]);
deepNestedContainer.resolve('IConfig');
示例2: Container
import { Container, LifeTime, Injectable } from 'container-ioc';
/*
By default, containers resolve singletons when using useClass and useFactory.
Default life time for all items in a container can be set by passing an option object to it's contructor with **defailtLifeTime** attribute.
Possible values: LifeTime.PerRequest (resolves instances) and LifeTime.Persistent (resolves singletons);
*/
const container = new Container({
defaultLifeTime: LifeTime.PerRequest
});
/*
You can also specify life time individually for each item in a container by specifying lifeTime attribute.
*/
@Injectable()
class ServiceA {}
/* With classes */
container.register([
{
token: 'ISerivceA',
useClass: ServiceA,
lifeTime: LifeTime.PerRequest
}
]);
/* With factories */
container.register([
{
token: 'IServiceB',
useFactory: () => {
示例3: Symbol
import { Container, Injectable } from 'container-ioc';
interface IService {
[key: string]: any;
}
const TSerivice = Symbol('IService');
@Injectable([TSerivice])
class App {
constructor(private service: IService) {}
}
const container = new Container();
container.register([
{ token: App, useClass: App },
{ token: TSerivice, useValue: {}}
]);
const app = container.resolve(App);
示例4: Container
import { Container } from 'container-ioc';
const container = new Container();
container.register([
{ token: 'IConfig', useValue: {}}
]);
const app = container.resolve('IConfig');