Giter Site home page Giter Site logo

vanthoainguyen / flatwhite.core Goto Github PK

View Code? Open in Web Editor NEW
4.0 2.0 0.0 34 KB

Flatwhite is an AOP library with MVC ActionFilter style using .NET Core dispatch proxy

C# 95.42% PowerShell 4.05% Shell 0.53%
aop netcore interceptors proxy dynamicproxy methodfilter actionfilter interceptor filter

flatwhite.core's Introduction

Flatwhite logo

Flatwhite.Core

Latest version NuGet Downloads Build Status Build status Test status License WTFPL

What is Flatwhite.Core?

Port from old Flatwhite package (.NET 4.5.2) to support only .NET CORE 2.1.x and doesn't require any extra packages

When to use Flatwhite.Core?

In your .NET core app, you have a need to intercept method calls so you possibly have 2 quick options:

  • Use Autofac.Extras and call EnableInterfaceInterceptor() on type registrations then create/register custom IInterceptor.
  • Or use Flatwhite, implement an MethodFilterAttribute and decorate on the methods on your interfaces which you want to intercept.

Flatwhite works for any methods

How to use Flatwhite.Core?

First, register the components

[HandleAllMethodExceptions]
interface IOrderService
{
	[FilterAttributeOnInterfaceMethod]
	Order GetById(int id);	

	[FilterAttributeOnInterfaceMethod]
	Task<Order> GetByIdAsync(int id);	
}

var serviceCollection = new ServiceCollection();
serviceCollection.UseFlatwhiteFilters();
serviceCollection.RegisterWithMethodFilters<IOrderService, OrderService>(ServiceLifetime.Singleton);

For additional logic before/after calling methods

Flatwhite is inspired by ASP.NET MVC ActionFilterAttribute, so it works quite similar. The base filter attribute has following methods. So simply implement your filter class and do whatever you want.

public abstract class MethodFilterAttribute : Attribute
{
    public virtual void OnMethodExecuting(MethodExecutingContext methodExecutingContext);    
    public virtual Task OnMethodExecutingAsync(MethodExecutingContext methodExecutingContext);   
    public virtual void OnMethodExecuted(MethodExecutedContext methodExecutedContext);    
    public virtual Task OnMethodExecutedAsync(MethodExecutedContext methodExecutedContext);    
}

If you decorate the filter on async methods, only OnMethodExecutingAsync and OnMethodExecutedAsync are called. During the filters are being executed, if the Result value is set to the MethodExecutingContext, the remaining filters will be ignored. However, all filters will be called OnMethodExecutedAsync or OnMethodExecuted unless there is an exception during invocation

For error handling

Similar to MethodFilterAttribute, you can implement ExceptionFilterAttribute to provide custom error handling logic. If the property MethodExceptionContext.Handled is true, all remaining ExceptionFilter will be ignored.

public abstract class ExceptionFilterAttribute : Attribute
{    
    public virtual void OnException(MethodExceptionContext exceptionContext);    
    public virtual Task OnExceptionAsync(MethodExceptionContext exceptionContext);       
}

Dependency injection on your filter

You can either use ServiceFilterAttribute or TypeFilterAttribute which work similar to .NET MVC Core

public class FilterAttributeOnClassMethod : MethodFilterAttribute
{
	private readonly ILogger _logger;

	public FilterAttributeOnClassMethod(ILogger logger)
	{
		_logger = logger;
	}
}

public class OrderService : IOrderService
{
	[ServiceFilter(typeof(FilterAttributeOnClassMethod))]
	public Order GetById(int id)
	{
		if (id <= 0) throw new ArgumentException("invalid order id");
		
		return new Order {Id = id, TotalAmount = id * DateTime.Now.Ticks};
	}
	
	[TypeFilter(typeof(FilterAttributeOnClassMethod))]
	public async Task<Order> GetByIdAsync(int id)
	{
		await Task.Delay(10);
		return GetById(id);
	}
}


var serviceCollection = new ServiceCollection();
serviceCollection.UseFlatwhiteFilters();
serviceCollection.RegisterWithMethodFilters<IOrderService, OrderService>(ServiceLifetime.Singleton);
// You must register the filter so ServiceProvider can resolve it later
serviceCollection.AddSingleton<FilterAttributeOnClassMethod>();

Create proxy without target

You can create an interface, have some method filters on its method and dont even need to implement the interface

public class FireProductDeletedEvent : MethodFilterAttribute
{	
}

public class HandleAllException : ExceptionFilterAttribute
{	
}


/// <summary>
/// This is the interface without any implementation, you can implement the main code in FireProductDeletedEvent and exception handling in HandleAllException
/// </summary>
[HandleAllException]
public interface IProductNotificationService
{	
	[FireProductDeletedEvent]
	Task FireProductEvent(Guid sku);
}

var serviceCollection = new ServiceCollection();
serviceCollection.UseFlatwhiteFilters();
serviceCollection.AddProxyWithoutTarget<IProductNotificationService>(ServiceLifetime.Singleton);

LICENCE

License WTFPL Troll

flatwhite.core's People

Stargazers

 avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

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.