2

I started to use InversifyJS in Dynamics 365 development. To give you some context, Dynamics allows you to extend the platform writing custom business logic (using JS) and attach it to defined form events. In this example, I want to instantiate my bussiness logic class and execute my custom code on the form onload event. The code should look like this:

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

As you can imagine, the onLoad function will be called by Dynamics 365 when the event takes place. The form context (ExternalContext in this example) will be passed as a parameter to the function. This object is really important because it allows to our code to interact with the controls that exist in the form, and it's this precisely object the one I want to inject to the BusinessLogic class.

BusinessLogic class:

@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);
}
}

Just another example dependency:

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

How do I register/inject the ExternalContext object that the platform passed to my onLoad method into my business class? I think about storing it in the container context but I'm sure there's a better way of doing it.

container.bind<ExternalContext>().toDynamicValue((context) => {
   //context??
});
Federico Jousset
  • 1,661
  • 14
  • 21

1 Answers1

0

Just in case someone else faces this scenario, I've implemeted this wrapping the container in a class with a private variable where I can store my ExternalContext and bind it using toDynamicValue() (I couldn't find a way of using the container context for this).

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

The bit I don't like about this approach is that requires to manually set the context before using the container, but I guess it's not that bad considering the alternatives:

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

There's probably a better way of doing this so please shout if you can figure it out.

Federico Jousset
  • 1,661
  • 14
  • 21