Module Control Interface (IModuleController)
namespace OutfitTool.API1
The IModuleController interface is the main channel for managing the module lifecycle. Through it, the host initializes the module, passes dependencies, retrieves the list of available commands, manages interface display, and handles notifications.
🔧 Key interface: Each module must implement
IModuleController. The host creates an instance of this class after successfully loading the module and uses it for all further interaction.
Interface Definition
using OutfitTool.API1.Dto;
using OutfitTool.API1.Logger;
using System.Windows.Media.Imaging;
namespace OutfitTool.API1;
public interface IModuleController
{
void SetLanguage(string language);
void Init(ILogger logger);
void Shutdown();
List<ICommand> GetCommandList();
BitmapImage? GetTaskbarIcon();
string? GetTaskbarIconText();
Notification? PopNotification();
void OpenSettings();
}
Method Descriptions
- void SetLanguage(string language)
-
Sets the interface language for the module. Called by the host when changing the language in the application or during module initialization if the language is already selected.
Parameters:
language— language code (e.g., "ru-RU", "en-US", "de-DE"). The module must translate all interface strings according to the provided locale.Features: If the module does not support the requested language, it is recommended to use the default language (e.g., English) or revert to the previous value.
- void Init(ILogger logger)
-
Initializes the module and passes a logger instance for recording diagnostic messages. Called immediately after creating the controller, before all other methods.
Parameters:
logger— logging interface provided by the host. The module must save it for further use.Important: All preparatory actions should be performed in this method: loading configuration, checking resource availability, initializing internal structures. In case of a critical error, an exception can be thrown — the host will handle it and disable the module.
- void Shutdown()
-
Signals the module about program termination. The module must correctly release all resources: close files, stop background threads, save state.
Features: After calling this method, the host will no longer interact with the module. The method must be synchronous and should not take too long (recommended to complete within a few seconds).
- List<ICommand> GetCommandList()
-
Returns a list of commands provided by the module. Commands are displayed in the program interface (e.g., in the context menu or on the toolbar).
Returns: A list of objects implementing the
ICommandinterface. Each command contains a name, icon, handler, and availability conditions.Note: The host may call this method multiple times (e.g., when updating the interface). The module must return an up-to-date list of commands, which may dynamically change depending on the module's state.
- BitmapImage? GetTaskbarIcon()
-
Provides an icon for temporary display in the notification area (system tray). Returns
nullif the module does not require a separate icon.Returns: An image in
BitmapImageformat (WPF). Recommended size — 16x16 or 32x32 pixels.The host constantly displays its own icon in the tray but polls all modules every 400 ms via TaskbarIcon(). When receiving an icon from a module, the host displays it in the tray. After receiving an icon from the next module, it displays it. When receiving null or at the end of the polling cycle, it displays its own icon again.
- string? GetTaskbarIconText()
-
Returns the tooltip text for the icon in the system tray. Displayed when hovering the cursor over the module's icon.
Returns: Tooltip text or
nullif no tooltip is required.Example: "Mail Agent: 3 unread messages".
- Notification? PopNotification()
-
Allows the module to send a notification to the user. The host calls this method periodically (e.g., every message processing cycle) to receive new notifications.
Returns: A
Notificationobject (from theOutfitTool.API1.Dtonamespace) ornullif there are no notifications.Working mechanism: The module can accumulate notifications in an internal queue. One notification is returned per call (FIFO). Notifications may contain a title, text, icon, and action on click.
Example: New email, completion of a long operation, reminder.
- void OpenSettings()
-
Called when the user requests to open the module settings window (e.g., through the context menu of the tray icon or in the module manager).
Expected behavior: The module must open a non-modal settings window. The window should be created as a separate WPF window.
Note: If the module has no configurable parameters, the method may do nothing or show an informational message.
Data Types Used in the Interface
ILogger Interface
namespace OutfitTool.API1.Logger;
public interface ILogger
{
void Debug(string log);
void Info(string log);
void Error(string log);
void Warning(string log);
void Critical(string log);
void Status(string log);
}
Logger provided by the host. All messages are automatically saved in the program's general log with the source module indicated.
Messages sent via the Status() method are displayed in the status bar of the main program window.
ICommand Interface
namespace OutfitTool.API1;
public interface ICommand
{
string Name { get; }
string Description { get; }
CommandContextMenu? ContextMenu { get; }
void Run();
}
Command displayed in the program interface. The host displays all commands from the list returned by GetCommandList().
Notification Class
namespace OutfitTool.API1.Dto;
public class Notification(string title, string message, string href)
{
public readonly string Message = message;
public readonly string Title = title;
public readonly string Href = href;
}
Module Lifecycle
Call sequence:
- The host creates an instance of
ModuleControllervia reflection.SetLanguage()is called with the current interface language.Init(logger)is called to initialize the module.- The host may repeatedly call
GetCommandList(),GetTaskbarIcon(),GetTaskbarIconText(), andPopNotification()during operation.- When the program terminates or the module is stopped,
Shutdown()is called.
Implementation Example
using System.Globalization;
using System.Timers;
using System.Windows.Media.Imaging;
using MailAgent.Settings;
using MailKit;
using OutfitTool.API1;
using OutfitTool.API1.Dto;
using OutfitTool.API1.Logger;
using Timer = System.Timers.Timer;
namespace MailAgent;
internal class ModuleController : IModuleController
{
private static Timer? _timer;
private Dictionary<UniqueId, MailDto> _unreadMessages = new();
private readonly Dictionary<UniqueId, MailDto> _notifiedMessages = new();
private readonly MailService _mailService = new();
private readonly SettingsManager<MailAgentSettings> _settingManager = new();
private ILogger? _logger;
public List<ICommand> GetCommandList()
{
return [];
}
public void SetLanguage(string language)
{
LocalizationHelper.SetLanguage(new CultureInfo(language));
}
public void Shutdown()
{
}
private void OnTimedEvent(object? source, ElapsedEventArgs e)
{
try
{
var settings = _settingManager.LoadSettings();
var tempUnreadMessages = new Dictionary<UniqueId, MailDto>();
foreach (var accountSettings in settings.GetAccountSettings())
{
try
{
// Here tempUnreadMessages is populated
var unreadAccountMessages = _mailService.CheckMail(accountSettings, settings.TimeToReconnect);
if (unreadAccountMessages == null) continue;
foreach (var unreadMessage in unreadAccountMessages)
{
tempUnreadMessages.Add(unreadMessage.Key, unreadMessage.Value);
}
}
catch (Exception ex) {
_logger?.Error(ex.Message);
}
}
// Here we transfer messages to unreadMessages (to ensure atomicity)
_unreadMessages = tempUnreadMessages;
}
catch (Exception ex) {
_logger?.Error(ex.ToString());
}
}
public BitmapImage? GetTaskbarIcon()
{
if (_unreadMessages.Count == 0)
{
return null;
}
return new BitmapImage(new Uri("pack://application:,,,/MailAgent;component/Resources/mail.ico"));
}
public string? GetTaskbarIconText()
{
if (_unreadMessages.Count == 0)
{
return null;
}
return "unread - " + _unreadMessages.Count;
}
public Notification? PopNotification()
{
var newUnreadMessages = new Dictionary<UniqueId, MailDto>();
foreach (var unreadMessage in _unreadMessages)
{
if (!_notifiedMessages.ContainsKey(unreadMessage.Key))
{
newUnreadMessages[unreadMessage.Key] = unreadMessage.Value;
}
}
Notification? notification = null;
if (newUnreadMessages.Count == 1)
{
var last = newUnreadMessages.Last().Value;
notification = new Notification(last.To + ": <" + last.From + ">", last.Subject, last.MailRef);
}
else if (newUnreadMessages.Count > 1)
{
var last = newUnreadMessages.Last().Value;
notification = new Notification(last.To + ":",
GetNotificationMessage(newUnreadMessages.Count), last.MailRef);
}
foreach (var unreadMessage in _unreadMessages)
{
_notifiedMessages[unreadMessage.Key] = unreadMessage.Value;
}
return notification;
}
private static string GetNotificationMessage(int count)
{
var (lastDigit, lastTwoDigits) = (count % 10, count % 100);
string messageEnding = (lastDigit == 1 && lastTwoDigits != 11)
? LocalizationHelper.GetString("NewMessageNominativeCase")
: (lastDigit is >= 2 and <= 4 && lastTwoDigits is < 12 or > 14)
? LocalizationHelper.GetString("NewMessageGenitiveSingular")
: LocalizationHelper.GetString("NewMessageGenitivePlural");
return $"{LocalizationHelper.GetString("YouHave")} {count} {messageEnding}";
}
public void OpenSettings()
{
var settings = _settingManager.LoadSettings();
var form = new SettingsForm(settings);
if (form.ShowDialog() != true) return;
var settingManager = new SettingsManager<MailAgentSettings>();
settingManager.SaveSettings(settings);
}
public void Init(ILogger logger)
{
_logger = logger;
var settings = _settingManager.LoadSettings();
_timer = new Timer(settings.CheckInterval * 1000);
_timer.Elapsed += OnTimedEvent;
_timer.AutoReset = true;
_timer.Enabled = true;
}
}
Rules and Recommendations
- Thread safety: Interface methods may be called from different threads. The implementation must be thread-safe.
- Performance: Methods should not take long to execute. If a long operation is required (e.g., mail synchronization), run it in a background thread and notify the user via notifications.
- Error handling: All exceptions, except in
Init(), should be handled within the module, logged via the providedILogger, and return to a safe state. - Resources: All resources (icons, images) must be embedded in the assembly as resources and loaded via
pack://URI.
⚠️ Important: The
Init()method may throw exceptions — this is a signal to the host that the module cannot work. In this case, the module will be disabled and not used. In all other methods, exceptions must be handled within the module.