Initial version

This commit is contained in:
EonaCat 2025-04-04 20:56:24 +02:00
parent 9b964dee75
commit 4612c852eb
11 changed files with 1284 additions and 125 deletions

91
.gitignore vendored
View File

@ -2,7 +2,7 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.rsuser
@ -14,9 +14,6 @@
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
@ -24,14 +21,10 @@ mono_crash.*
[Rr]eleases/
x64/
x86/
[Ww][Ii][Nn]32/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
@ -45,10 +38,9 @@ Generated\ Files/
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
# NUNIT
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
@ -63,9 +55,6 @@ project.lock.json
project.fragment.lock.json
artifacts/
# ASP.NET Scaffolding
ScaffoldingReadMe.txt
# StyleCop
StyleCopReport.xml
@ -91,7 +80,6 @@ StyleCopReport.xml
*.tmp_proj
*_wpftmp.csproj
*.log
*.tlog
*.vspscc
*.vssscc
.builds
@ -133,6 +121,9 @@ _ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
@ -143,11 +134,6 @@ _TeamCity*
.axoCover/*
!.axoCover/settings.json
# Coverlet is a free, cross platform Code Coverage Tool
coverage*.json
coverage*.xml
coverage*.info
# Visual Studio code coverage results
*.coverage
*.coveragexml
@ -195,8 +181,6 @@ PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
@ -221,14 +205,12 @@ BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
!*.[Cc]ache/
# Others
ClientBin/
@ -272,9 +254,6 @@ ServiceFabricBackup/
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
@ -295,17 +274,6 @@ node_modules/
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio 6 auto-generated project file (contains which files were open etc.)
*.vbp
# Visual Studio 6 workspace and project file (working project files containing files to include in project)
*.dsw
*.dsp
# Visual Studio 6 technical files
*.ncb
*.aps
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
@ -321,6 +289,10 @@ paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
# CodeRush personal settings
.cr/personal
@ -362,53 +334,10 @@ ASALocalRun/
# Local History for Visual Studio
.localhistory/
# Visual Studio History (VSHistory) files
.vshistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/
# Fody - auto-generated XML schema
FodyWeavers.xsd
# VS Code files for those working on multiple tools
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
*.code-workspace
# Local History for Visual Studio Code
.history/
# Windows Installer files from build outputs
*.cab
*.msi
*.msix
*.msm
*.msp
# JetBrains Rider
*.sln.iml
# ---> VisualStudioCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
!.vscode/*.code-snippets
# Local History for Visual Studio Code
.history/
# Built Visual Studio Code Extensions
*.vsix

25
EonaCat.EventKit.sln Normal file
View File

@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.4.33110.190
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EonaCat.EventKit", "EonaCat.EventKit\EonaCat.EventKit.csproj", "{68268BF4-0451-4434-BB07-65DB829CEF51}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{68268BF4-0451-4434-BB07-65DB829CEF51}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{68268BF4-0451-4434-BB07-65DB829CEF51}.Debug|Any CPU.Build.0 = Debug|Any CPU
{68268BF4-0451-4434-BB07-65DB829CEF51}.Release|Any CPU.ActiveCfg = Release|Any CPU
{68268BF4-0451-4434-BB07-65DB829CEF51}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {FBE67F06-CBF4-4673-A8E8-EF31FC3038E8}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,40 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<PackageId>EonaCat.EventKit</PackageId>
<Authors>EonaCat (Jeroen Saey)</Authors>
<Company>EonaCat (Jeroen Saey)</Company>
<Description>EventKit - The Ultimate C# Event Management Toolkit</Description>
<PackageProjectUrl>https://git.saey.me/EonaCat/EonaCat.EventKit</PackageProjectUrl>
<RepositoryUrl>https://git.saey.me/EonaCat/EonaCat.EventKit</RepositoryUrl>
<PackageTags>event, subscription, analyzer, roslyn, weak-reference, events, kit, EonaCat, Jeroen, Saey</PackageTags>
<LangVersion>latest</LangVersion>
<Title>EonaCat.EventKit</Title>
<Copyright>EonaCat (Jeroen Saey)</Copyright>
<PackageIcon>icon.png</PackageIcon>
<PackageReadmeFile>README.md</PackageReadmeFile>
<RepositoryType>git</RepositoryType>
<PackageLicenseFile>LICENSE</PackageLicenseFile>
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
</PropertyGroup>
<ItemGroup>
<None Include="..\icon.png">
<Pack>True</Pack>
<PackagePath>\</PackagePath>
</None>
<None Include="..\LICENSE">
<Pack>True</Pack>
<PackagePath>\</PackagePath>
</None>
<None Include="..\README.md">
<Pack>True</Pack>
<PackagePath>\</PackagePath>
</None>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis" Version="3.8.0" />
<PackageReference Include="System.Diagnostics.DiagnosticSource" Version="9.0.3" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,45 @@
/*
EonaCat.EventKit
Copyright 2025 EonaCat (Jeroen Saey)
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
https://EonaCat.com/license/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
OF SOFTWARE BY EONACAT (JEROEN SAEY)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License
*/
using System;
using System.Collections.Generic;
using System.Text;
namespace EonaCat.EventKit
{
public static class EventKitExtensions
{
public static void SubscribeToEvent(this object target, string eventName, Action<string, EventArgs?> onEvent)
{
EventSubscriptionManager.Subscribe(target, eventName, onEvent);
}
public static void UnsubscribeFromEvent(this object target, string eventName)
{
EventSubscriptionManager.Unsubscribe(target, eventName);
}
}
}

View File

@ -0,0 +1,51 @@
/*
EonaCat.EventKit
Copyright 2025 EonaCat (Jeroen Saey)
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
https://EonaCat.com/license/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
OF SOFTWARE BY EONACAT (JEROEN SAEY)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License
*/
using System;
using System.Diagnostics;
namespace EonaCat.EventKit
{
public static class EventSubscriptionLogger
{
private static readonly DiagnosticListener _diagnosticListener = new DiagnosticListener("EonaCat.EventKit");
public static void LogSubscription(object target, string eventName)
{
if (_diagnosticListener.IsEnabled("EventSubscribed"))
{
_diagnosticListener.Write("EventSubscribed", new { Target = target, EventName = eventName });
}
}
public static void LogUnsubscription(object target, string eventName)
{
if (_diagnosticListener.IsEnabled("EventUnsubscribed"))
{
_diagnosticListener.Write("EventUnsubscribed", new { Target = target, EventName = eventName });
}
}
}
}

View File

@ -0,0 +1,432 @@
/*
EonaCat.EventKit
Copyright 2025 EonaCat (Jeroen Saey)
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
https://EonaCat.com/license/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
OF SOFTWARE BY EONACAT (JEROEN SAEY)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
namespace EonaCat.EventKit
{
public static class EventSubscriptionManager
{
private static readonly Dictionary<object, Dictionary<string, Delegate>> _subscriptions = new();
private static readonly HashSet<string> _activeEventStack = new();
private static readonly Dictionary<string, int> _eventCount = new();
public static void SubscribeWithCountLogging(
object target,
string eventName,
Action<string, EventArgs?>? onEvent = null,
SubscribeOptions? options = null)
{
Subscribe(target, eventName, onEvent, options);
if (!_eventCount.ContainsKey(eventName))
{
_eventCount[eventName] = 0;
}
Action<object, EventArgs?> handler = (sender, args) =>
{
_eventCount[eventName]++;
Console.WriteLine($"[EonaCat.EventKit] {eventName} fired {_eventCount[eventName]} times.");
onEvent?.Invoke(eventName, args);
};
Subscribe(target, eventName, handler, options);
}
public static void SubscribeWithExecutionContext(
object target,
string eventName,
Action<string, EventArgs?> onEvent,
SynchronizationContext? syncContext = null,
SubscribeOptions? options = null)
{
syncContext ??= SynchronizationContext.Current;
Action<object, EventArgs?> handler = (sender, args) =>
{
if (syncContext != null)
{
syncContext.Post(_ =>
{
onEvent(eventName, args);
}, null);
}
else
{
onEvent(eventName, args);
}
};
Subscribe(target, eventName, handler, options);
}
public static async void SubscribeWithExpiry(
object target,
string eventName,
Action<string, EventArgs?> onEvent,
TimeSpan expiryDuration,
SubscribeOptions? options = null)
{
Subscribe(target, eventName, onEvent, options);
await Task.Delay(expiryDuration);
Unsubscribe(target, eventName);
}
public static void SubscribeWithRetry(
object target,
string eventName,
Action<string, EventArgs?> onEvent,
int maxRetries = 3,
TimeSpan? retryInterval = null,
SubscribeOptions? options = null)
{
retryInterval ??= TimeSpan.FromSeconds(1);
var retries = 0;
Action<object, EventArgs?> handler = (sender, args) =>
{
while (retries < maxRetries)
{
try
{
onEvent(eventName, args);
break;
}
catch (Exception ex)
{
retries++;
if (retries == maxRetries)
{
Console.WriteLine($"[EonaCat.EventKit] {eventName} failed after {retries} retries. Error: {ex.Message}");
}
else
{
Console.WriteLine($"[EonaCat.EventKit] Retrying {eventName} due to error: {ex.Message}");
Task.Delay(retryInterval.Value).Wait();
}
}
}
};
Subscribe(target, eventName, handler, options);
}
[AttributeUsage(AttributeTargets.Event)]
public class EventFilterAttribute : Attribute
{
public string FilterName { get; }
public EventFilterAttribute(string filterName)
{
FilterName = filterName;
}
}
public static void SubscribeAllWithFilter(
object target,
string filterName,
Action<string, EventArgs?> onEvent,
SubscribeOptions? options = null)
{
foreach (var evt in target.GetType().GetEvents())
{
var attribute = evt.GetCustomAttribute<EventFilterAttribute>();
if (attribute != null && attribute.FilterName == filterName)
{
Subscribe(target, evt.Name, onEvent, options);
}
}
}
public static void SubscribeConcurrently(
object target,
string eventName,
Func<string, EventArgs?, Task> onEventAsync,
SubscribeOptions? options = null)
{
async void Handler(object sender, EventArgs args)
{
async Task HandleEventAsync()
{
try
{
await onEventAsync(eventName, args);
}
catch (Exception ex)
{
if (options?.HandleExceptions ?? true)
{
Console.WriteLine($"[EonaCat.EventKit] Error handling event {eventName}: {ex.Message}");
}
}
}
await HandleEventAsync();
}
Subscribe(target, eventName, Handler, options);
}
public static int GetEventCount(string eventName)
{
return _eventCount.ContainsKey(eventName) ? _eventCount[eventName] : 0;
}
public static void SubscribeAll(
object target,
Func<EventInfo, bool>? filter = null,
Action<string, EventArgs?>? onEvent = null,
SubscribeOptions? options = null)
{
foreach (var evt in target.GetType().GetEvents())
{
if (filter == null || filter(evt))
{
Subscribe(target, evt.Name, onEvent, options);
}
}
}
public static void Subscribe(
object target,
string eventName,
Action<string, EventArgs?>? onEvent = null,
SubscribeOptions? options = null)
{
if (target == null)
{
return;
}
options ??= new();
var type = target.GetType();
var eventInfo = type.GetEvent(eventName);
if (eventInfo == null || !eventInfo.EventHandlerType.IsSubclassOf(typeof(Delegate)))
{
return;
}
if (_subscriptions.TryGetValue(target, out var dict) && dict.ContainsKey(eventName))
{
return;
}
Action<object, EventArgs?> handler = (s, e) =>
{
if (options.ReentrancySafe && _activeEventStack.Contains(eventName))
{
return;
}
try
{
_activeEventStack.Add(eventName);
onEvent?.Invoke(eventName, e);
}
catch (Exception ex)
{
if (options.HandleExceptions)
{
Console.WriteLine($"[EonaCat.EventKit] Error in handler for {eventName}: {ex.Message}");
}
}
finally
{
_activeEventStack.Remove(eventName);
}
};
var del = CreateDelegate(eventInfo.EventHandlerType, handler);
eventInfo.AddEventHandler(target, del);
if (!_subscriptions.ContainsKey(target))
{
_subscriptions[target] = new();
}
_subscriptions[target][eventName] = del;
}
public static void SubscribeWeak(
object target,
string eventName,
Action<string, EventArgs?>? onEvent = null,
SubscribeOptions? options = null)
{
if (target == null)
{
return;
}
options ??= new();
var type = target.GetType();
var eventInfo = type.GetEvent(eventName);
if (eventInfo == null || !eventInfo.EventHandlerType.IsSubclassOf(typeof(Delegate)))
{
return;
}
if (_subscriptions.TryGetValue(target, out var dict) && dict.ContainsKey(eventName))
{
return;
}
WeakEventHandler weakHandler = new WeakEventHandler(target, eventName, onEvent);
var del = CreateDelegate(eventInfo.EventHandlerType, weakHandler.Handler);
eventInfo.AddEventHandler(target, del);
if (!_subscriptions.ContainsKey(target))
{
_subscriptions[target] = new();
}
_subscriptions[target][eventName] = del;
}
public static void Unsubscribe(object target, string eventName)
{
if (!_subscriptions.TryGetValue(target, out var dict) || !dict.ContainsKey(eventName))
{
return;
}
var eventInfo = target.GetType().GetEvent(eventName);
eventInfo?.RemoveEventHandler(target, dict[eventName]);
dict.Remove(eventName);
if (dict.Count == 0)
{
_subscriptions.Remove(target);
}
}
public static void UnsubscribeAll(object target)
{
if (!_subscriptions.TryGetValue(target, out var dict))
{
return;
}
foreach (var (eventName, handler) in dict)
{
target.GetType().GetEvent(eventName)?.RemoveEventHandler(target, handler);
}
_subscriptions.Remove(target);
}
public static IEnumerable<(string EventName, Delegate Handler)> ListSubscriptions(object target)
{
return _subscriptions.TryGetValue(target, out var dict)
? dict.Select(kv => (kv.Key, kv.Value))
: Enumerable.Empty<(string, Delegate)>();
}
private static Delegate CreateDelegate(Type eventType, Action<object, EventArgs?> handler)
{
return Delegate.CreateDelegate(eventType, handler.Target!, handler.Method);
}
public static void SubscribeWithAutoUnsubscribeOnDispose(
object target,
string eventName,
Action<string, EventArgs?>? onEvent = null,
SubscribeOptions? options = null)
{
Subscribe(target, eventName, onEvent, options);
if (target is IDisposable disposable)
{
var disposableWithEvent = new DisposableWithEvent(disposable);
disposableWithEvent.Disposed += (sender, args) =>
{
// Unsubscribe from the event when disposed
Unsubscribe(target, eventName);
};
}
}
public class DisposableWithEvent : IDisposable
{
private readonly IDisposable _disposableTarget;
// Event to be triggered when Dispose() is called
public event EventHandler? Disposed;
public DisposableWithEvent(IDisposable disposableTarget)
{
_disposableTarget = disposableTarget ?? throw new ArgumentNullException(nameof(disposableTarget));
}
public void Dispose()
{
OnDisposed();
_disposableTarget.Dispose();
}
protected virtual void OnDisposed()
{
Disposed?.Invoke(this, EventArgs.Empty);
}
}
public class WeakEventHandler
{
private WeakReference _targetReference;
private string _eventName;
private Action<string, EventArgs?> _onEvent;
public WeakEventHandler(object target, string eventName, Action<string, EventArgs?> onEvent)
{
_targetReference = new WeakReference(target);
_eventName = eventName;
_onEvent = onEvent;
}
public void Handler(object? sender, EventArgs? args)
{
if (_targetReference.IsAlive)
{
_onEvent(_eventName, args);
}
else
{
Unsubscribe(sender, _eventName);
}
}
}
}
}

View File

@ -0,0 +1,165 @@
/*
EonaCat.EventKit
Copyright 2025 EonaCat (Jeroen Saey)
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
https://EonaCat.com/license/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
OF SOFTWARE BY EONACAT (JEROEN SAEY)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License
*/
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
[Generator]
public class EventSubscriptionSourceGenerator : ISourceGenerator
{
private const string EventHandlerPrefix = "GeneratedEventHandler";
public void Initialize(GeneratorInitializationContext context)
{
// Initialization logic (if any) can go here
}
public void Execute(GeneratorExecutionContext context)
{
var syntaxReceiver = context.SyntaxReceiver as SyntaxReceiver;
if (syntaxReceiver == null)
{
return;
}
foreach (var classDeclaration in syntaxReceiver.Classes)
{
var className = classDeclaration.Identifier.Text;
var eventSubscriptions = new StringBuilder();
var unsubscribeMethods = new StringBuilder();
var eventHandlers = new StringBuilder();
foreach (var eventMember in classDeclaration.Members.OfType<EventDeclarationSyntax>())
{
var eventName = eventMember.Identifier.Text;
var eventType = eventMember.Type.ToString();
var eventHandlerMethod = GenerateEventHandlerMethod(eventMember);
// Generate subscription code
eventSubscriptions.AppendLine($@"
EonaCat.EventKit.EventSubscriptionManager.SubscribeWeak({className}.Instance, ""{eventName}"", {eventHandlerMethod});");
// Generate unsubscription code
unsubscribeMethods.AppendLine($@"
EonaCat.EventKit.EventSubscriptionManager.Unsubscribe({className}.Instance, ""{eventName}"");");
// Add the generated event handler to the class
eventHandlers.AppendLine(eventHandlerMethod);
}
var sourceCode = $@"
// <auto-generated/>
// This file is auto-generated by EonaCat.EventKit.
// Do not edit this file directly.
/*
EonaCat.EventKit
Copyright 2025 EonaCat (Jeroen Saey)
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
https://EonaCat.com/license/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
OF SOFTWARE BY EONACAT (JEROEN SAEY)
Licensed under the Apache License, Version 2.0 (the ""License"");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an ""AS IS"" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License
*/
namespace GeneratedEventSubscriptions
{{
public static class {className}EventSubscriptions
{{
public static void Subscribe()
{{
{eventSubscriptions}
}}
public static void Unsubscribe()
{{
{unsubscribeMethods}
}}
// Event Handlers
{eventHandlers}
}}
}}";
// Add the generated code as a new source file
context.AddSource($"{className}EventSubscriptions.g.cs", SourceText.From(sourceCode, Encoding.UTF8));
}
}
private string GenerateEventHandlerMethod(EventDeclarationSyntax eventDeclaration)
{
var eventType = eventDeclaration.Type.ToString();
var eventHandlerMethodName = $"{EventHandlerPrefix}_{eventDeclaration.Identifier.Text}Handler";
// Check if the event handler has parameters
var eventHandlerParameters = eventType.Contains(",")
? eventType.Split(',').Select(param => param.Trim()).ToList()
: new List<string> { eventType };
var eventHandlerParametersText = string.Join(", ", eventHandlerParameters.Select(p => $"{p} args"));
return $@"
private static void {eventHandlerMethodName}(object sender, {string.Join(", ", eventHandlerParameters)})
{{
// Your event handler logic here
// For example: log the event
Console.WriteLine($""{eventDeclaration.Identifier.Text} event fired with parameters: {string.Join(", ", eventHandlerParameters)}"");
}}";
}
}
public class SyntaxReceiver : ISyntaxReceiver
{
public List<ClassDeclarationSyntax> Classes { get; } = new List<ClassDeclarationSyntax>();
public void OnVisitSyntaxNode(SyntaxNode syntaxNode)
{
if (syntaxNode is ClassDeclarationSyntax classDeclaration)
{
Classes.Add(classDeclaration);
}
}
}

View File

@ -0,0 +1,34 @@
/*
EonaCat.EventKit
Copyright 2025 EonaCat (Jeroen Saey)
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
https://EonaCat.com/license/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
OF SOFTWARE BY EONACAT (JEROEN SAEY)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License
*/
namespace EonaCat.EventKit
{
public class SubscribeOptions
{
public bool ReentrancySafe { get; set; } = false;
public bool UseWeakReference { get; set; } = false;
public bool HandleExceptions { get; set; } = true;
}
}

213
LICENSE
View File

@ -1,73 +1,204 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
https://EonaCat.com/license/
1. Definitions.
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
OF SOFTWARE BY EONACAT (JEROEN SAEY)
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
1. Definitions.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
END OF TERMS AND CONDITIONS
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
APPENDIX: How to apply the Apache License to your work.
END OF TERMS AND CONDITIONS
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
APPENDIX: How to apply the Apache License to your work.
Copyright 2025 EonaCat
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
Copyright [yyyy] [name of copyright owner]
http://www.apache.org/licenses/LICENSE-2.0
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

311
README.md
View File

@ -1,3 +1,310 @@
# EonaCat.EventKit
Detect subscribed/unsubscribed events
# 🎯 EonaCat.EventKit - The Ultimate C# Event Management Toolkit
`EonaCat.EventKit` is a hybrid runtime + Roslyn analyzer library
that makes subscribing/unsubscribing and managing events safer, smarter, and simpler.
---
## 🚀 Features
### ✅ Runtime API
- 🔄 **Subscribe/Unsubscribe to any event** dynamically
- 🌐 **Subscribe to all events** of a class with optional filtering
- 🛡️ **Reentrancy-safe** handlers
- 💥 **Safe execution** with built-in exception handling
- 📖 **Track current subscriptions**
- 🔎 **Event forwarding** for diagnostics/logging
- 🧹 **Automatic unsubscription on disposal**
- 🧠 **Weak event subscriptions** for better memory management
- ⏳ **Event expiry** for timed unsubscription
- 🔄 **Retry event handling** for transient errors
- 🔥 **Concurrent event handling** for async operations
### 🧠 Roslyn Analyzers
- ⚠️ **Detect duplicate subscriptions**
- 🧹 **Detect missing unsubscriptions**
- 🔧 **CodeFix**: auto-insert `-=` for unsubscribing
---
## 📦 Installation
**Install via NuGet:**
```bash
dotnet add package EonaCat.EventKit
```
## 🛠️ Usage Example
Simple Event Subscription
```csharp
var button = new Button();
EonaCat.EventKit.EventSubscriptionManager.Subscribe(button, "Click", (name, args) =>
{
Console.WriteLine($"Clicked: {args}");
});
// Later
EonaCat.EventKit.EventSubscriptionManager.Unsubscribe(button, "Click");
```
**Subscribe All Events With Filter**
```csharp
EonaCat.EventKit.EventSubscriptionManager.SubscribeAll(
someControl,
evt => evt.Name.StartsWith("On"),
(name, args) => Console.WriteLine($"{name} fired!")
);
```
Concurrent Event Handling
```csharp
EonaCat.EventKit.EventSubscriptionManager.SubscribeConcurrently(
someControl,
"Click",
async (name, args) =>
{
await SomeAsyncMethod();
Console.WriteLine($"{name} clicked asynchronously.");
});
```
**Event Subscription with Expiry**
```csharp
EonaCat.EventKit.EventSubscriptionManager.SubscribeWithExpiry(
someControl,
"Click",
(name, args) =>
{
Console.WriteLine($"{name} clicked.");
},
TimeSpan.FromSeconds(30) // Expire the subscription after 30 seconds
);
```
**Auto Unsubscribe on Dispose**
```csharp
EonaCat.EventKit.EventSubscriptionManager.SubscribeWithAutoUnsubscribeOnDispose(
someControl,
"Click",
(name, args) =>
{
Console.WriteLine($"{name} clicked.");
});
```
🛠️ Advanced Usage
Subscribe with Event Count Logging
```csharp
EonaCat.EventKit.EventSubscriptionManager.SubscribeWithCountLogging(
someControl,
"Click",
(name, args) =>
{
Console.WriteLine($"{name} clicked.");
});
```
**Retry Logic for Event Handling**
```csharp
EonaCat.EventKit.EventSubscriptionManager.SubscribeWithRetry(
someControl,
"Click",
(name, args) =>
{
Console.WriteLine($"{name} clicked.");
});
```
**Subscribe with Execution Context (Thread-Safe)**
```csharp
EonaCat.EventKit.EventSubscriptionManager.SubscribeWithExecutionContext(
someControl,
"Click",
(name, args) =>
{
Console.WriteLine($"{name} clicked.");
});
```
## 🔎 Using the EventSubscriptionLogger
The EventSubscriptionLogger is a useful tool for tracking and logging event subscriptions. This can help you understand the flow of event subscriptions and ensure that everything is behaving as expected.
**Enabling Event Subscription Logging**
To enable event subscription logging, use the EventSubscriptionLogger in combination with EventSubscriptionManager to log all subscriptions and unsubscriptions.
```csharp
// Enable event subscription logging
EonaCat.EventKit.EventSubscriptionLogger.Enable();
// Subscribe to an event
var button = new Button();
EonaCat.EventKit.EventSubscriptionManager.Subscribe(button, "Click", (name, args) =>
{
Console.WriteLine($"Clicked: {args}");
});
// Later, unsubscribe from the event
EonaCat.EventKit.EventSubscriptionManager.Unsubscribe(button, "Click");
// Disable event subscription logging (optional)
EonaCat.EventKit.EventSubscriptionLogger.Disable();
```
Custom Event Subscription Logger
You can also create a custom logger to output the subscription information in a way that fits your needs
```csharp
EonaCat.EventKit.EventSubscriptionLogger.Enable(log =>
{
// Do custom logging action: For example, log to a file or console
Console.WriteLine($"Event subscribed: {log.EventName} to {log.Target}");
});
```
## 👀 Analyzer Diagnostics
|ID| TITLE | FIX|
|--|--|--|
| EVT001 | Duplicate event subscription | Suggest review|
| EVT002 | Missing event unsubscription | Auto-fix in code|
## 🧹 Memory Management Features
##### - 🧹 Automatic unsubscription on disposal to prevent memory leaks.
##### - 🧠 Weak event subscriptions to help with garbage collection.
##### - ⏳ Event expiry to automatically unsubscribe after a specified duration.
##### - 🔄 Retry logic for transient errors during event handling.
##### - 🔥 Concurrent event handling for async operations.
##### - 🧠 Weak event subscriptions to prevent memory leaks when the target object is no longer referenced.
##### - 💡 Reentrancy-safe handling to avoid recursive event triggering during handler execution.
## ⚙️ Customization Options
**SubscribeOptions**
- ReentrancySafe : Ensures handlers aren't invoked while already executing for the same event.
- UseWeakReference: Enables weak references for event subscriptions to help with garbage collection.
- HandleExceptions: Configures whether exceptions in event handlers should be logged or handled silently.
**Example**
```csharp
EonaCat.EventKit.EventSubscriptionManager.Subscribe(
someControl,
"Click",
(name, args) =>
{
Console.WriteLine($"Clicked: {args}");
},
new SubscribeOptions { ReentrancySafe = true, UseWeakReference = true });
```
## 🧑‍💻 Subscribing to Events in Regular Classes
EonaCat.EventKit isn't limited to UI controls; you can subscribe to events in regular classes that define events as well.
**Example with a Custom Class (Non-Control)**
Lets create a class MyCustomClass that has a few events. We'll use the source generator to generate subscription and unsubscription methods, and then use them in the same way.
**Step 1: Define a Custom Class with Events**
```csharp
public class MyCustomClass
{
// Define events
public event EventHandler SomeEvent;
public event EventHandler<string> MessageEvent;
// Methods to fire events
public void TriggerSomeEvent()
{
SomeEvent?.Invoke(this, EventArgs.Empty);
}
public void TriggerMessageEvent(string message)
{
MessageEvent?.Invoke(this, message);
}
}
```
**Step 2: Generated Subscription Code**
After running the EventSubscriptionSourceGenerator, you would get a generated class MyCustomClassEventSubscriptions,
which will contain the subscription and unsubscription methods. Here's what the generated code would look like:
```csharp
namespace GeneratedEventSubscriptions
{
public static class MyCustomClassEventSubscriptions
{
public static void Subscribe()
{
// Subscribing to events
EonaCat.EventKit.EventSubscriptionManager.SubscribeWeak(MyCustomClass.Instance, "SomeEvent", GeneratedEventHandler_SomeEventHandler);
EonaCat.EventKit.EventSubscriptionManager.SubscribeWeak(MyCustomClass.Instance, "MessageEvent", GeneratedEventHandler_MessageEventHandler);
}
public static void Unsubscribe()
{
// Unsubscribing from events
EonaCat.EventKit.EventSubscriptionManager.Unsubscribe(MyCustomClass.Instance, "SomeEvent");
EonaCat.EventKit.EventSubscriptionManager.Unsubscribe(MyCustomClass.Instance, "MessageEvent");
}
// Event Handlers
private static void GeneratedEventHandler_SomeEventHandler(object sender, EventArgs args)
{
Console.WriteLine("SomeEvent triggered.");
}
private static void GeneratedEventHandler_MessageEventHandler(object sender, string message)
{
Console.WriteLine($"MessageEvent triggered with message: {message}");
}
}
}
```
**Step 3: Using the Subscription and Unsubscription in Code**
Now, you can use the generated subscription and unsubscription methods just like before
but with a regular class instead of a control. Heres how to use it in your program:
```csharp
using System;
using GeneratedEventSubscriptions; // Import the generated namespace
class Program
{
static void Main(string[] args)
{
// Create instance of the custom class
var myClass = new MyCustomClass();
// Subscribe to events
MyCustomClassEventSubscriptions.Subscribe();
// Trigger events
myClass.TriggerSomeEvent(); // Should trigger SomeEvent handler
myClass.TriggerMessageEvent("Hello, World!"); // Should trigger MessageEvent handler
// Optionally, unsubscribe from events
MyCustomClassEventSubscriptions.Unsubscribe();
// Trigger events again after unsubscription (no output as it is unsubscribed)
myClass.TriggerSomeEvent();
myClass.TriggerMessageEvent("Goodbye!"); // No output
}
}
```
## 🔄 Conclusion
EonaCat.EventKit offers a flexible and powerful event management toolkit that works seamlessly with both UI controls and regular classes.
Whether you're handling events in UI elements or business logic classes,
the toolkit provides robust features like subscription management, weak references, automatic unsubscription,
and even retry logic for transient errors.

BIN
icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 88 KiB