.NetCore AOP

2021/8/1 23:37:28

本文主要是介绍.NetCore AOP,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

新建项目:AspectCoreExtensions.Sample

  <ItemGroup>
    <PackageReference Include="AspectCore.Extensions.Autofac" Version="2.2.0" />
    <PackageReference Include="Autofac.Extensions.DependencyInjection" Version="7.1.0" />
  </ItemGroup>

Program.cs

using Autofac.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace AspectCoreExtensions.Sample
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args).UseServiceProviderFactory(new AutofacServiceProviderFactory())
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
}

Startup.cs

using AspectCore.Configuration;
using AspectCore.DependencyInjection;
using AspectCore.DynamicProxy;
using AspectCore.Extensions.Autofac;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

namespace AspectCoreExtensions.Sample
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddScoped<ITaskService, TaskService>();//或者A
        }

        public void ConfigureContainer(ContainerBuilder builder)
        {
            var serviceContext = new ServiceContext();
            //serviceContext.AddType<ITaskService, TaskService>();//或者B
            //builder.RegisterType<TaskService>().As<ITaskService>().InstancePerLifetimeScope();//或者C

            //调用Populate扩展方法在Autofac中注册已经注册到ServiceContainer中的服务(如果有)。注:此方法调用应在RegisterDynamicProxy之前
            builder.Populate(serviceContext);

            //调用RegisterDynamicProxy扩展方法在Autofac中注册动态代理服务和动态代理配置
            builder.RegisterDynamicProxy(serviceContext.Configuration, config =>
            {
                config.Interceptors.AddTyped<MethodExecuteLoggerInterceptor>(Predicates.ForService("*Service"));
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
    public interface ITaskService
    {
        bool Run();
    }

    public class TaskService : ITaskService
    {
        public bool Run()
        {
            return true;
        }
    }
    public class MethodExecuteLoggerInterceptor : AbstractInterceptor
    {
        public override async Task Invoke(AspectContext context, AspectDelegate next)
        {
            var stopwatch = Stopwatch.StartNew();
            await next(context);
            stopwatch.Stop();
            Console.WriteLine("Executed method {0}.{1}.{2} ({3}) in {4}ms,返回值:{5}",
                context.ImplementationMethod.DeclaringType.Namespace,
                context.ImplementationMethod.DeclaringType.Name,
                context.ImplementationMethod.Name,
                context.ImplementationMethod.DeclaringType.Assembly.GetName().Name,
                stopwatch.ElapsedMilliseconds,
                context.ReturnValue
            );
        }
    }
}

WeatherForecastController.cs

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace AspectCoreExtensions.Sample.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private readonly ILogger<WeatherForecastController> _logger;
        private readonly ITaskService _taskService;

        public WeatherForecastController(ILogger<WeatherForecastController> logger, ITaskService taskService)
        {
            _logger = logger;
            _taskService = taskService;
        }

        [HttpGet]
        public IActionResult Get()
        {
            _taskService.Run();
            return Ok(true);
        }
    }
}



这篇关于.NetCore AOP的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程