.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);
        }
    }
}

上一篇:使用Docker安装Jenkins和使用Jenkins来发布和代理.NetCore项目


下一篇:netcore 模块化框架源码