Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

AOP implementation for .Net

License

NotificationsYou must be signed in to change notification settings

fasetto/SharpAspect

Repository files navigation

Nuget
dotnet add package SharpAspect

SharpAspect is an AOP(Aspect-Oriented Programming) package for .Net
It depends onCastle.Core DynamicProxy. Currently only supports method and property interception.

Take advantage of run-time interception for your next project.

Check thewiki page for more samples and documentation.

Defining & Mapping your Interceptors

Method Interception

publicclassLogAttribute:MethodInterceptorAttribute{}// You must specify the attribute for the interceptor.[InterceptFor(typeof(LogAttribute))]publicclassLogInterceptor:MethodInterceptor{privatereadonlyLoggerlogger;// The Logger dependency will be resolved using Microsoft's DI containerpublicLogInterceptor(Loggerlogger){this.logger=logger;}// MethodInterceptor class provides OnBefore, OnAfter and OnError methods.// You can override these methods to seperate the logic you don't want in your actual method.publicoverrideTaskOnBefore(IInvocationinvocation){logger.LogInfo($"[Log] Executing method:{invocation.TargetType.FullName}.{invocation.Method.Name}");returnTask.FromResult(Task.CompletedTask);}}

Simple logger.

publicclassLogger{publicvoidLogInfo(stringmessage){System.Console.WriteLine($"[+]{message}");}}

Registering your services

privatestaticIServiceProviderConfigureServices(){returnnewServiceCollection().AddSingleton<Logger>().AddTransient<IRocket,Rocket>()// Call this, after you registered your services..EnableDynamicProxy().BuildServiceProvider();}
publicinterfaceIRocket{stringName{get;set;}voidLaunch();}// Enabled interception for service type IRocket[Intercept(typeof(IRocket))]publicclassRocket:IRocket{publicstringName{get;set;}[Log]publicvoidLaunch(){System.Console.WriteLine("Launching rocket in 3...2.....1 🚀");}}
staticvoidMain(string[]args){varservices=ConfigureServices();varrocket=services.GetRequiredService<IRocket>();rocket.Name="Falcon 9";rocket.Launch();System.Console.WriteLine($"{rocket.Name} launched successfully. (:");}

Sample Output

[+] [Log] Executing method: SharpAspect.Sample.Rocket.LaunchLaunching rocketin 3...2.....1 🚀Falcon 9 launched successfully. (:

[8]ページ先頭

©2009-2025 Movatter.jp