GithubHelp home page GithubHelp logo

sharpaspect's Introduction

Getting Started

Nuget
dotnet add package SharpAspect

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

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

Check the wiki page for more samples and documentation.

Defining & Mapping your Interceptors

Method Interception

public class LogAttribute: MethodInterceptorAttribute
{
}

// You must specify the attribute for the interceptor.

[InterceptFor(typeof(LogAttribute))]
public class LogInterceptor: MethodInterceptor
{
    private readonly Logger logger;

    // The Logger dependency will be resolved using Microsoft's DI container
    public LogInterceptor(Logger logger)
    {
        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.
    public override Task OnBefore(IInvocation invocation)
    {
        logger.LogInfo($"[Log] Executing method: {invocation.TargetType.FullName}.{invocation.Method.Name}");

        return Task.FromResult(Task.CompletedTask);
    }
}

Simple logger.

public class Logger
{
    public void LogInfo(string message)
    {
        System.Console.WriteLine($"[+] {message}");
    }
}

Registering your services

private static IServiceProvider ConfigureServices()
{
    return new ServiceCollection()
        .AddSingleton<Logger>()
        .AddTransient<IRocket, Rocket>()

        // Call this, after you registered your services.
        .EnableDynamicProxy()

        .BuildServiceProvider();
}
public interface IRocket
{
    string Name { get; set; }

    void Launch();
}

// Enabled interception for service type IRocket

[Intercept(typeof(IRocket))]
public class Rocket: IRocket
{
    public string Name { get; set; }

    [Log]
    public void Launch()
    {
        System.Console.WriteLine("Launching rocket in 3...2.....1 ๐Ÿš€");
    }
}
static void Main(string[] args)
{
    var services = ConfigureServices();

    var rocket = services.GetRequiredService<IRocket>();

    rocket.Name = "Falcon 9";
    rocket.Launch();

    System.Console.WriteLine($"{rocket.Name} launched successfully. (:");
}

Sample Output

[+] [Log] Executing method: SharpAspect.Sample.Rocket.Launch
Launching rocket in 3...2.....1 ๐Ÿš€
Falcon 9 launched successfully. (:

sharpaspect's People

Contributors

dependabot-preview[bot] avatar dependabot[bot] avatar fasetto avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

sharpaspect's Issues

Stop and then quit

Hello,

If the conditions are met in the onbefore method, is it possible to turn it off completely?

I wanted to use sharpaspect for cache, but should not log into method if conditions are met before method.

Can it be done?

 public override Task OnBefore(IInvocation invocation)
        {
                var methodName = string.Format(
                     "{0}.{1}.{2}",
                     invocation.Method.ReflectedType.Namespace,
                     invocation.Method.ReflectedType.Name,
                     invocation.Method.Name
                     );

            var arguments = invocation.Arguments.ToList();
            var key = string.Format("{0}({1})", methodName,
                string.Join(",", arguments.Select(x => x != null ? x.ToString() : "<Null>"))
                );
            if (_cacheManager.IsAdd(key))
            {
                invocation.ReturnValue = _cacheManager.Get<object>(key); //
                 If you have any, do not enter the method, this answer will return
                
                return Task.FromResult(Task.CompletedTask);
            }

            return Task.FromResult(Task.CompletedTask);
          
        }

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.