Skip to content
Ian Johnson edited this page Apr 5, 2017 · 5 revisions

Grace as a library does not do any interception itself. The intention is for developers to use a library such as Castle.Core to do proxy generation.

Below is an example of a C# extension that can be used to wire up Castle Proxies for interception.

var container = new DependencyInjectionContainer
{ 
  c => 
  {
    c.Export<SomeClass>().As<ISomeInterface>();
    c.Intercept<ISomeInterface,CustomInterceptor>();
  }
};

public static class InterceptExtensions
{
  public static IFluentDecoratorStrategyConfiguration Intercept<TService, TInterceptor>(
            this IExportRegistrationBlock block) where TInterceptor : IInterceptor
  {
     Type decoratorType;

     var tService = typeof(TService);

     if (tService.GetTypeInfo().IsInterface)
     {
        decoratorType = ProxyBuilder.CreateInterfaceProxyTypeWithTargetInterface(tService, new Type[0],
                    ProxyGenerationOptions.Default);
     }
     else if (tService.GetTypeInfo().IsClass)
     {
        decoratorType = ProxyBuilder.CreateClassProxyTypeWithTarget(tService, new Type[0],
                    ProxyGenerationOptions.Default);
     }
     else
     {
       throw new Exception($"Service type must be interface or class");
     }

     return block.ExportDecorator(decoratorType).As(tService).WithCtorParam<TInterceptor, IInterceptor[]>(i => new IInterceptor[] { i });
  }

  private static DefaultProxyBuilder ProxyBuilder => _proxyBuilder ?? (_proxyBuilder = new DefaultProxyBuilder());

  private static DefaultProxyBuilder _proxyBuilder;
}
Clone this wiki locally