.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的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2022-03-01沐雪多租宝商城源码从.NetCore3.1升级到.Net6的步骤
- 2024-11-15C#中怎么从PEM格式的证书中提取公钥?-icode9专业技术文章分享
- 2024-11-14云架构设计——如何用diagrams.net绘制专业的AWS架构图?
- 2024-05-08首个适配Visual Studio平台的国产智能编程助手CodeGeeX正式上线!C#程序员必备效率神器!
- 2024-03-30C#设计模式之十六迭代器模式(Iterator Pattern)【行为型】
- 2024-03-29c# datetime tryparse
- 2024-02-21list find index c#
- 2024-01-24convert toint32 c#
- 2024-01-24Advanced .Net Debugging 1:你必须知道的调试工具
- 2024-01-24.NET集成IdGenerator生成分布式全局唯一ID