Injecting properties

We can now combine the results of both arrays to match the parameter name with the type name in our decorator code, as follows:

for (let i = 0; i < splitArr.length; i++) { 
    let propertyName = splitArr[i]; 
    let typeName = parameterTypeArray[i]; 
 
    console.log(` 
        parameterName : ${propertyName}  
        is of type    : ${typeName.name}`); 
} 

Here, we are looping through the splitArr array (which contains our parameter names), and using the same index on the parameterTypeArray property to match property names with type names. The result is as follows:

parameterName : _settings  
is of type    : IISystemSettings 

parameterName : testParameter is of type : String

With this information at hand, we can now use JavaScript to inject the property that we require, as follows:

Object.defineProperty(classDefinition.prototype, propertyName, { 
    get : function() { 
        return ServiceLocatorGeneric.resolve( 
            eval(typeName) 
        ); 
    } 
}); 

Here, we are using the Object.defineProperty function that JavaScript provides to create a property at runtime and attach it to the definition of our class. The defineProperty function takes three parameters. The first parameter is the prototype of the class to be modified. The second parameter is the propertyName itself, and the third parameter is the definition of the property. Our property definition is a simple getter function, that then calls the ServiceLocatorGeneric.resolve function, passing in the typeName function.  Note how we have called the eval function, passing it the typeName function that we retrieved from our parameterTypeArray. This step is necessary in order to send the class definition to the service locator instead of a simple string.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.19.30.232