在.net core中使用属性注入

​ 众所周知core自带的IOC容器,并不支持属性注入,如果要使用属性注入的话,就需要使用第三方解决方案.比如鼎鼎有名的autofact,还有国人出品的AspectCore-Framework.根据他blog上的介绍,性能大概是前者的5倍.参考

  1. 添加包

    AspectCore.Extensions.Hosting
    
  2. 在需要注入的属性上加上特性

     [FromServiceContext]
     public PerformingContext JobContext { get; set; }
    
  3. IserviceCollection引入我们的组建

      public static IHostBuilder CreateHostBuilder(string[] args) =>
      Host.CreateDefaultBuilder(args)
      .UseServiceContext() //注入Aspect
      .ConfigureAppConfiguration((context, builder) =>
      {
      	builder.AddNacosConfiguration(builder.Build().GetSection("nacos"));
      })
      .ConfigureWebHostDefaults(webBuilder =>
      {
      	webBuilder.UseStartup<Startup>();
      });
    
  4. Startup中注入PerformingContext

        services.AddTransient<PerformingContext>(PerformingContext);
    
  5. Service里要配置Controller又Ioc框架接手

services.AddMvc().AddControllersAsServices();

即可完成.

posted on 2021-09-06 12:09  隨風.NET  阅读(767)  评论(0编辑  收藏  举报

导航