Home Backend Development C#.Net Tutorial A brief discussion on AspectCore_Practical skills

A brief discussion on AspectCore_Practical skills

Jun 15, 2017 pm 01:49 PM
asp.net core

This article mainly introduces the Asp.Net Core lightweight Aop solution: AspectCore. Friends who need it can refer to it

What is AspectCore Project?

AspectCore Project is a lightweight Aop (Aspect-oriented programming) solution suitable for the Asp.Net Core platform. It better follows the modular development concept of Asp.Net Core. Using AspectCore can be more Easily build low-coupling, easily scalable web applications. AspectCore uses Emit to implement efficient dynamic proxy without relying on any third-party Aop library.

Start using AspectCore

Start Visual Studio. From the File menu, choose New > Project. Select the ASP.NET Core Web Application project template and create a new ASP.NET Core Web Application project.


public class CustomInterceptorAttribute : InterceptorAttribute
{
  public async override Task Invoke(IAspectContext context, AspectDelegate next)
  {
    try
    {
      Console.WriteLine("Before service call");
      await next(context);
    }
    catch (Exception)
    {
      Console.WriteLine("Service threw an exception!");
      throw;
    }
    finally
    {
      Console.WriteLine("After service call");
    }
   }
 }
Copy after login

Define the ICustomService interface and its implementation class CustomService:


public interface ICustomService
{
  [CustomInterceptor]
  void Call();
}
public class CustomService : ICustomService
{
  public void Call()
  {
    Console.WriteLine("service calling...");
  }
}
Copy after login

Inject ICustomService in HomeController:


public class HomeController : Controller
{
  private readonly ICustomService _service;
  public HomeController(ICustomService service)
  {
    _service = service;
  }
  public IActionResult Index()
  {
    _service.Call();
    return View();
  }
}
Copy after login

Register ICustomService, and then configure the container to create a proxy type in ConfigureServices:


public IServiceProvider ConfigureServices(IServiceCollection services)
{
  services.AddTransient<ICustomService, CustomService>();
  services.AddMvc();
  services.AddAspectCore();
  return services.BuildAspectCoreServiceProvider();
}
Copy after login

Interceptor configuration. First install the AspectCore.Extensions.Configuration package:


PM> Install-Package AspectCore.Extensions.Configuration
Copy after login

Global interceptor. Use the

overloaded method of AddAspectCore(Action<AspectCoreOptions>), where AspectCoreOptions provides InterceptorFactories to register the global interceptor:


 services.AddAspectCore(config =&gt;
 {
   config.InterceptorFactories.AddTyped&lt;CustomInterceptorAttribute&gt;();
 });
Copy after login

Global interceptor with constructor parameters, add a constructor with parameters in

CustomInterceptorAttribute:


public class CustomInterceptorAttribute : InterceptorAttribute
{
  private readonly string _name;
  public CustomInterceptorAttribute(string name)
  {
    _name = name;
  }
  public async override Task Invoke(AspectContext context, AspectDelegate next)
  {
    try
    {
      Console.WriteLine(&quot;Before service call&quot;);
      await next(context);
    }
    catch (Exception)
    {
      Console.WriteLine(&quot;Service threw an exception!&quot;);
      throw;
    }
    finally
    {
      Console.WriteLine(&quot;After service call&quot;);
    }
  }
}
Copy after login

Modify global interceptor registration:


services.AddAspectCore(config =&gt;
{
   config.InterceptorFactories.AddTyped&lt;CustomInterceptorAttribute&gt;(args: new object[] { &quot;custom&quot; });
});
Copy after login

As a global interceptor for the service. Add in ConfigureServices:


services.AddTransient&lt;CustomInterceptorAttribute&gt;(provider =&gt; new CustomInterceptorAttribute(&quot;service&quot;));
Copy after login

Modify global interceptor registration:


services.AddAspectCore(config =&gt;
{
  config.InterceptorFactories.AddServiced&lt;CustomInterceptorAttribute&gt;();
});
Copy after login

acts on a specific Service or Method Global interceptor, the following code demonstrates the global interceptor acting on classes with the Service suffix:


services.AddAspectCore(config =&gt;
{
  config.InterceptorFactories.AddTyped&lt;CustomInterceptorAttribute&gt;(method =&gt; method.DeclaringType.Name.EndsWith(&quot;Service&quot;));
});
Copy after login

Specific global interception using the

wildcard character Device:


services.AddAspectCore(config =&gt;
{
  config.InterceptorFactories.AddTyped&lt;CustomInterceptorAttribute&gt;(PredicateFactory.ForService(&quot;*Service&quot;));
});
Copy after login

Provide NonAspectAttribute in AspectCore to prevent Service or Method from being proxied:


[NonAspect]
public interface ICustomService
{
  void Call();
}
Copy after login

Supported at the same time The configuration is ignored globally and wildcards are also supported:



 services.AddAspectCore(config =&gt;
 {
   //App1命名空间下的Service不会被代理
   config.NonAspectOptions.AddNamespace(&quot;App1&quot;);
   //最后一级为App1的命名空间下的Service不会被代理
   config.NonAspectOptions.AddNamespace(&quot;*.App1&quot;);
   //ICustomService接口不会被代理
   config.NonAspectOptions.AddService(&quot;ICustomService&quot;);
   //后缀为Service的接口和类不会被代理
   config.NonAspectOptions.AddService(&quot;*Service&quot;);
   //命名为Query的方法不会被代理
   config.NonAspectOptions.AddMethod(&quot;Query&quot;);
   //后缀为Query的方法不会被代理
   config.NonAspectOptions.AddMethod(&quot;*Query&quot;);
 });
Copy after login

Dependency Injection in the interceptor. Supports property injection, constructor injection and service locator patterns in interceptors. Property injection, property tags with public get and
set permissions in the interceptor [AspectCore.Abstractions.FromServices] (different from Microsoft.AspNetCore.Mvc. FromServices) feature, you can automatically inject this property, such as:


public class CustomInterceptorAttribute : InterceptorAttribute
{
  [AspectCore.Abstractions.FromServices]
  public ILogger&lt;CustomInterceptorAttribute&gt; Logger { get; set; }
  public override Task Invoke(AspectContext context, AspectDelegate next)
  {
    Logger.LogInformation(&quot;call interceptor&quot;);
    return next(context);
  }
}
Copy after login

Constructor injection needs to make the interceptor as a Service. In addition to the global interceptor, it can still be Use ServiceInterceptor to enable the interceptor to be activated from DI:


public interface ICustomService
{
  [ServiceInterceptor(typeof(CustomInterceptorAttribute))]
  void Call();
}
Copy after login

Service Locator pattern. The interceptor context AspectContext can obtain the current Scoped ServiceProvider:


public class CustomInterceptorAttribute : InterceptorAttribute
{
  public override Task Invoke(AspectContext context, AspectDelegate next)
  {
    var logger = context.ServiceProvider.GetService&lt;ILogger&lt;CustomInterceptorAttribute&gt;&gt;();
    logger.LogInformation(&quot;call interceptor&quot;);
    return next(context);
  }
}
Copy after login

Using Autofac and AspectCore. AspectCore natively supports integrating Autofac. We need to install the following two nuget packages:


PM&gt; Install-Package Autofac.Extensions.DependencyInjection
PM&gt; Install-Package AspectCore.Extensions.Autofac
Copy after login

AspectCore provides the RegisterAspectCore extension method to register the services required by the dynamic proxy in the Autofac Container and provide The AsInterfacesProxy and AsClassProxy extension methods enable proxies for interfaces and classes. Modify the ConfigureServices method to:


public IServiceProvider ConfigureServices(IServiceCollection services)
{
  services.AddMvc();
  var container = new ContainerBuilder();
  container.RegisterAspectCore();
  container.Populate(services);
  container.RegisterType&lt;CustomService&gt;().As&lt;ICustomService&gt;().InstancePerDependency().AsInterfacesProxy();

  return new AutofacServiceProvider(container.Build());
}
Copy after login

The above is the detailed content of A brief discussion on AspectCore_Practical skills. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot Article Tags

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to enable Core Isolation's memory integrity feature in Windows 11 How to enable Core Isolation's memory integrity feature in Windows 11 May 10, 2023 pm 11:49 PM

How to enable Core Isolation's memory integrity feature in Windows 11

What does computer core mean? What does computer core mean? Sep 05, 2022 am 11:24 AM

What does computer core mean?

How to Fix Processor Thermal Trip Error in Windows 11/10 [Fix] How to Fix Processor Thermal Trip Error in Windows 11/10 [Fix] Apr 17, 2023 am 08:13 AM

How to Fix Processor Thermal Trip Error in Windows 11/10 [Fix]

Is CORE coin worth holding for the long term? Is CORE coin worth investing in? Is CORE coin worth holding for the long term? Is CORE coin worth investing in? Feb 29, 2024 pm 05:34 PM

Is CORE coin worth holding for the long term? Is CORE coin worth investing in?

.NET Core cross-platform application development practice: a seamless journey from Windows to Linux and macOS .NET Core cross-platform application development practice: a seamless journey from Windows to Linux and macOS Feb 26, 2024 pm 12:55 PM

.NET Core cross-platform application development practice: a seamless journey from Windows to Linux and macOS

What is core under linux What is core under linux Mar 23, 2023 am 10:00 AM

What is core under linux

Surface Laptop Studio is coming to Europe, here's how much it'll cost Surface Laptop Studio is coming to Europe, here's how much it'll cost May 10, 2023 pm 05:34 PM

Surface Laptop Studio is coming to Europe, here's how much it'll cost

IFA 2024 | Core Ultra Series 2: In Lunar Lake, Intel introduces its most efficient x86 CPU yet IFA 2024 | Core Ultra Series 2: In Lunar Lake, Intel introduces its most efficient x86 CPU yet Sep 04, 2024 am 06:38 AM

IFA 2024 | Core Ultra Series 2: In Lunar Lake, Intel introduces its most efficient x86 CPU yet

See all articles