2

我开始在 Dynamics 365 开发中使用 InversifyJS。为了给您一些上下文,Dynamics 允许您扩展平台编写自定义业务逻辑(使用 JS)并将其附加到定义的表单事件。在此示例中,我想实例化我的业务逻辑类并在表单 onload 事件上执行我的自定义代码。代码应如下所示:

namespace Example {
    export function onLoad(context: ExternalContext) {
        set bl = container.resolve<BusinessLogic>(BusinessLogic);
        bl.doSomething();
    }
}

可以想象,onLoad当事件发生时,Dynamics 365 将调用该函数。表单上下文(ExternalContext在本例中)将作为参数传递给函数。这个对象非常重要,因为它允许我们的代码与表单中存在的控件进行交互,而我想要注入到中的正是这个对象BusinessLogic

业务逻辑类:

@injectable()
export class BusinessLogic {
    protected readonly _context: ExternalContext;
    protected readonly _otherDependency: OtherDependency;

 constructor(
    @inject(ExternalContext) formContext: ExternalContext, 
    @inject(OtherDependency) otherDependency: OtherDependency) {
    this._formContext = formContext;
    this._otherDependency = otherDependency;
}

doSomething() {
    this._otherDependency.foo(this._context.value1);
}
}

只是另一个示例依赖项:

@injectable()
export class OtherDependency {
    foo(propertyValue: string) {
        // do stuff...
    }
}

如何ExternalContext将平台传递给我的方法的对象注册/注入onLoad到我的业务类中?我考虑将它存储在容器上下文中,但我确信有更好的方法来做到这一点。

container.bind<ExternalContext>().toDynamicValue((context) => {
   //context??
});
4

1 回答 1

0

以防万一其他人面临这种​​情况,我已经实现了将容器包装在一个带有私有变量的类中,我可以在其中存储ExternalContext和绑定它toDynamicValue()(我找不到为此使用容器上下文的方法)。

    this.container.bind<ExternalContext>(ExternalContext).toDynamicValue(() => {
        return this._externalContext;
    });

我不喜欢这种方法的一点是需要在使用容器之前手动设置上下文,但考虑到替代方案,我想这还不错:

namespace Example {
    export function onLoad(context: ExternalContext) {
    externalContainer.setContext(context);  // <----- :(       
    set bl = externalContainer.container.resolve<BusinessLogic>(BusinessLogic);
            bl.doSomething();
        }
    }

可能有更好的方法可以做到这一点,所以如果你能弄清楚,请大喊大叫。

于 2019-06-28T13:16:20.870 回答