1. 程式人生 > >AOP框架Dora.Interception 3.0 [2]: 實現原理

AOP框架Dora.Interception 3.0 [2]: 實現原理

和所有的AOP框架一樣,我們必須將正常的方法呼叫進行攔截,才能將應用到當前方法上的所有攔截器納入當前呼叫鏈。Dora.Interception採用IL Eimit的方式實現對方法呼叫的攔截,接下來我們就來聊聊大致的實現原理。

一、與依賴注入框架的無縫整合

由於Dora.Interception是為.NET Core定製的AOP框架,而依賴注入是.NET Core基本的程式設計方式,所以Dora.Interception最初就是作為一個依賴注入框架的擴充套件而涉及的。我們知道.NET Core的依賴注入框架支援三種服務例項提供方式。由於Dora.Interception最終會利用IL Emit的方式動態生成目標例項的型別,所以它只適合第一種服務註冊方式。

  • 如果註冊的是一個服務型別,最終會選擇一個匹配的建構函式來建立服務例項;
  • 如果註冊的是一個服務例項建立工廠,那麼目標服務例項就由該工廠來建立;
  • 如果註冊的是一個服務例項,那麼它會直接作為目標服務例項。

二、兩種攔截方式

.NET Core的依賴注入框架採用ServiceDescriptor物件來描述服務註冊。攔截器最終會註冊到ImplementationType 屬性表示的實現型別上,所以Dora.Interception需要根據該型別生成一個可以被攔截的代理型別。針對ServiceType屬性表示的服務型別的不同,我們會採用不同的程式碼生成方式。

針對介面

如果註冊服務時提供的是一個介面和它的實現型別,我們會按照如下的方式來生成可被攔截的代理型別。假設介面和實現型別分別為IFoobar和Foobar,那麼我們會生成一個同樣實現IFoobar介面的FoobarProxy型別。FoobarProxy物件是對Foobar物件的封裝,對於它實現的方法來說,如果沒有攔截器應用到Foobar型別對應的方法上,它只需要呼叫封裝的這個Foobar物件對應的方法就可以了。反之,針對攔截器的呼叫將會注入到FoobarProxy實現的方法中。

針對型別

如果註冊是提供的服務型別並不是一個介面,而是一個型別,比如服務型別和實現型別都是Foobar,上述的程式碼生成機制就不適用了。此時我們要求Foobar必須是一個非封閉(Sealed)的型別,而且攔截器只能應用到它的虛方法上。基於這種假設,我們生成的代理型別FoobarProxy實際上市Foobar的子類,如果攔截器應用到Foobar的某個虛方法上,FoobarProxy只需要重寫這個方法將應用的攔截器注入到方法呼叫管道中。

三、ICodeGenerator & ICodeGeneratorFactory

上述針對IL Emit的動態代理型別生成體現在如下這個ICodeGenerator介面上,該介面唯一的方法GenerateInterceptableProxyClass會根據提供的上下文資訊生成可被攔截的代理型別。作為程式碼生成上下文的的CodeGenerationContext物件來說,它除了提供服務註冊的型別和實現型別之外,它還提供了IInterceptorRegistry物件。

public interface ICodeGenerator
{
    Type GenerateInterceptableProxyClass(CodeGenerationContext  context);
}

public class CodeGenerationContext
{   
    public Type InterfaceOrBaseType { get; }
    public Type TargetType { get; }
    public IInterceptorRegistry Interceptors { get; }

    public CodeGenerationContext(Type baseType, IInterceptorRegistry interceptors );   
    public CodeGenerationContext(Type @interface, Type targetType, IInterceptorRegistry interceptors);
}

IInterceptorRegistry介面在Dora.Interception中表示某個型別針對攔截器的註冊。它的IsEmpty表示攔截器是否應用到目標型別的任意成員中;IsInterceptable方法幫助我們確定指定的方法是否應用了攔截器;應用到某個方法的所有攔截器可以通過GetInterceptor方法提取出來。

public interface IInterceptorRegistry
{   
    bool IsEmpty { get; }
    InterceptorDelegate GetInterceptor(MethodInfo methodInfo);
    bool IsInterceptable(MethodInfo methodInfo);
    MethodInfo GetTargetMethod(MethodInfo methodInfo);
}

如果我們需要得到針對某個型別的IInterceptorRegistry物件,可以呼叫IInterceptorResolver介面的如下兩個GetInterceptors方法過載。

public interface IInterceptorResolver
{    
    IInterceptorRegistry GetInterceptors(Type initerfaceType, Type targetType);
    IInterceptorRegistry GetInterceptors(Type targetType);
}

與程式碼生成相關的還具有如下這個ICodeGeneratorFactory介面,它是建立ICodeGenerator的工廠。

四、ServiceDescriptor的轉換

由於服務例項最終是通過依賴注入框架提供的,而最終得到怎樣的服務例項則由最初的服務註冊決定。為了讓依賴注入框架能夠提供一個可被攔截的代理物件,而不是原始的目標物件,我們必須改變初始的服務註冊,為此我們定義瞭如下這個InterceptableServiceDescriptor。如下面的程式碼片段所示,InterceptableServiceDescriptor實際是一個基於工廠的ServiceDescriptor,建立代理物件的邏輯體現在GetImplementationFactory方法返回Func<IServiceProvider, object>物件上。

public sealed class InterceptableServiceDescriptor : ServiceDescriptor, IInterceptableServiceDescriptor
{
    private readonly Type _targetType;
        : base(serviceType, GetImplementationFactory(serviceType, implementationType), lifetime)
    {
        if (serviceType.IsGenericTypeDefinition)
        {
            throw new ArgumentException("Open generic type (generic type definition) is not support", nameof(serviceType));
        }
        _targetType = implementationType;
    }

    Type IInterceptableServiceDescriptor.TargetType => _targetType;

    private static Func<IServiceProvider, object> GetImplementationFactory(Type serviceType, Type implementationType)
    {
        return serviceProvider =>
        {
            var interceptorResolver = serviceProvider.GetRequiredService<IInterceptorResolver>();
            var codeGeneratorFactory = serviceProvider.GetRequiredService<ICodeGeneratorFactory>();
            var factoryCache = serviceProvider.GetRequiredService<IInterceptableProxyFactoryCache>();
            if (serviceType.IsInterface)
            {
                var interceptors = interceptorResolver.GetInterceptors(serviceType, implementationType);
                if (interceptors.IsEmpty)
                {
                    return ActivatorUtilities.CreateInstance(serviceProvider, implementationType);
                }
                else
                {
                    var target = ActivatorUtilities.CreateInstance(serviceProvider, implementationType);
                    return factoryCache.GetInstanceFactory(serviceType, implementationType).Invoke(target);
                }
            }
            else
            {
                var interceptors = interceptorResolver.GetInterceptors(implementationType);
                if (interceptors.IsEmpty)
                {
                    return ActivatorUtilities.CreateInstance(serviceProvider, implementationType);
                }
                else
                {
                    return factoryCache.GetTypeFactory(implementationType).Invoke(serviceProvider);
                }
            }
        };
    }
}

我們可以利用提供的如下的擴充套件方法直接建立InterceptableServiceDescriptor 物件作為服務註冊。

public static class AddInterceptionExtensions
{   
    public static IServiceCollection AddInterceptable(this IServiceCollection services, Type serviceType, Type implementationType, ServiceLifetime lifetime);
   
    public static IServiceCollection AddTransientInterceptable(this IServiceCollection services, Type serviceType, Type implementationType);
    public static IServiceCollection AddScopedInterceptable(this IServiceCollection services, Type serviceType, Type implementationType);
    public static IServiceCollection AddSingletonInterceptable(this IServiceCollection services, Type serviceType, Type implementationType);
    public static IServiceCollection AddInterceptable<TService, TImplementation>(this IServiceCollection services, ServiceLifetime lifetime);
    public static IServiceCollection AddTransientInterceptable<TService, TImplementation>(this IServiceCollection services);
    public static IServiceCollection AddScopedInterceptable<TService, TImplementation>(this IServiceCollection services);
    public static IServiceCollection AddSingletonInterceptable<TService, TImplementation>(this IServiceCollection services);

    public static IServiceCollection TryAddInterceptable(this IServiceCollection services, Type serviceType, Type implementationType, ServiceLifetime lifetime);
    public static IServiceCollection TryAddTransientInterceptable(this IServiceCollection services, Type serviceType, Type implementationType);
    public static IServiceCollection TryAddScopedInterceptable(this IServiceCollection services, Type serviceType, Type implementationType);
    public static IServiceCollection TryAddSingletonInterceptable(this IServiceCollection services, Type serviceType, Type implementationType);
    public static IServiceCollection TryAddInterceptable<TService, TImplementation>(this IServiceCollection services, ServiceLifetime lifetime);
    public static IServiceCollection TryAddInterceptable<TService, TImplementation>(this IServiceCollection services);
    public static IServiceCollection TryAddScopedInterceptable<TService, TImplementation>(this IServiceCollection services);
    public static IServiceCollection TryAddSingletonInterceptable<TService, TImplementation>(this IServiceCollection services);

    public static IServiceCollection TryAddEnumerableInterceptable(this IServiceCollection services, Type serviceType, Type implementationType, ServiceLifetime lifetime);
    public static IServiceCollection TryAddEnumerableInterceptable<TService, TImplementation>(this IServiceCollection services, ServiceLifetime lifetime)
}

五、另一種改變服務註冊的方式

如果我們依然希望採用預設提供的服務註冊API,那麼我們可以將服務註冊的轉換實現在利用IServiceCollection集合建立IServiceProvider物件的時候,為此我們定義瞭如下這個BuildInterceptableServiceProvider擴充套件方法。順便說一下,另一個AddInterception擴充套件方法用來註冊Dora.Interception框架自身的一些核心服務。BuildInterceptableServiceProvider方法內部會呼叫這個方法,如果沒有采用這種方式來建立IServiceProvider物件,AddInterception擴充套件方法必須顯式呼叫。

public static class ServiceCollectionExtensions
{   
    public static IServiceProvider BuildInterceptableServiceProvider(this IServiceCollection services, Action<InterceptionBuilder> configure = null);
    public static IServiceCollection AddInterception(this IServiceCollection services, Action<InterceptionBuilder> configure = null);
}

六、InterceptableServiceProviderFactory

.NET Core依賴注入框架利用自定義的IServiceProviderFactory<TContainerBuilder>實現與第三方依賴注入框架的整合。如下這個的InterceptableServiceProviderFactory是我們為Dora.Interception定義的實現型別。

public sealed class InterceptableServiceProviderFactory : IServiceProviderFactory<IServiceCollection>
{   
    public InterceptableServiceProviderFactory(ServiceProviderOptions options, Action<InterceptionBuilder> configure);   
    public IServiceCollection CreateBuilder(IServiceCollection services);
    public IServiceProvider CreateServiceProvider(IServiceCollection containerBuilder);
}

為了在服務承載應用(含ASP.NET Core應用)更好地使用Dora.Interception,可以呼叫我們為IHostBuilder定義的UseInterceptableServiceProvider擴充套件方法,該方法會幫助我們完成針對InterceptableServiceProviderFactory的註冊。

public static class HostBuilderExtensions
{
    public static IHostBuilder UseInterceptableServiceProvider(this IHostBuilder builder,ServiceProviderOptions options = null,Action<InterceptionBuilder> configure = null);
}

我們在《AOP框架Dora.Interception 3.0 [1]: 程式設計體驗》提供的演示程式(如下所示)正是呼叫了這個UseInterceptableServiceProvider方法。

public class Program
{
    public static void Main(string[] args)
    {
        Host.CreateDefaultBuilder()
            .UseInterceptableServiceProvider(configure: Configure)
            .ConfigureWebHostDefaults(buider => buider.UseStartup<Startup>())
            .Build()
            .Run();

        static void Configure(InterceptionBuilder interceptionBuilder)
        {
            interceptionBuilder.AddPolicy(policyBuilder => policyBuilder
                .For<CacheReturnValueAttribute>(order: 1, cache => cache
                    .To<SystemClock>(target => target
                        .IncludeMethod(clock => clock.GetCurrentTime(default)))));
        }
    }
}


AOP框架Dora.Interception 3.0 [1]: 程式設計體驗
AOP框架Dora.Interception 3.0 [2]: 實現原理
AOP框架Dora.Interception 3.0 [3]: 攔截器設計
AOP框架Dora.Interception 3.0 [4]: 基於特性的攔截器註冊
AOP框架Dora.Interception 3.0 [5]: 基於策略的攔截器註冊
AOP框架Dora.Interception 3.0 [6]: 自定義攔截器註冊