Kentico CMS 7.0 Developer's Guide

Loading service classes from App_Code

Loading service classes from App_Code

Previous topic Next topic Mail us feedback on this topic!  

Loading service classes from App_Code

Previous topic Next topic JavaScript is required for the print function Mail us feedback on this topic!  

For translation services defined in the App_Code folder, you need to ensure that the system loads the appropriate class when calling the given service. You can find additional information related to this topic in Registering custom classes in App_Code.

 

1. Create a dedicated class in the App_Code folder (or Old_App_Code if the project is installed as a web application). For example, name the class ClassLoader.cs.

 

2. Edit the class and add the following reference:

 

[C#]

 

using CMS.SettingsProvider;

 

3. Delete the default class declaration and its content. Instead, extend the CMSModuleLoader partial class and define a new attribute inheriting from CMS.SettingsProvider.CMSLoaderAttribute:

 
[C#]

 

[ClassLoader]
public partial class CMSModuleLoader
{
    /// <summary>
    /// Attribute class for loading custom classes.
    /// </summary>
    private class ClassLoader : CMSLoaderAttribute
    {
 
    }
}

 

4. Add the following code into the ClassLoader attribute class:

 

 

InfoBox_Exclamation

 

Warning!

 

This loads the sample machine and human translation providers created according to the instructions in this chapter.

 

You need to adjust the code to match the names of your own custom service classes. If you do not have the sample classes in your web project, delete or comment out the corresponding cases in the switch statement.

 

 

[C#]

 

/// <summary>
/// Called automatically when the application starts.
/// </summary>
public override void Init()
{
    // Assigns a handler for the OnGetCustomClass event.
    ClassHelper.OnGetCustomClass += ClassHelper_OnGetCustomClass;
}
 
/// <summary>
/// Gets a custom class object based on the given parameters.
/// </summary>
private void ClassHelper_OnGetCustomClass(object sender, ClassEventArgs e)
{
    if (e.Object == null)
    {
        // Checks the name of the requested class.
        switch (e.ClassName)
        {
            // Gets an instance of the SampleMachineTS class.
            case "SampleMachineTS":
                e.Object = new SampleMachineTS();
                break;
 
            // Gets an instance of the SampleTS class.
            case "SampleTS":
                e.Object = new SampleTS();
                break;
        }
    }
}

 

The value of the ClassName property of the ClassHelper_OnGetCustomClass handler's ClassEventArgs parameter matches the Service provider class name specified for the service in the system. The handler checks the class name to identify which translation service is being requested and then passes on an instance of the appropriate class.