ASP.NET Core 3.1 中使用Autofac实现属性注入

1.在项目NuGet程序包中引用:Autofac.Extensions.DependencyInjection

2.Program程序入口类中替换容器

 public static IHostBuilder CreateHostBuilder(string[] args) => 
            Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup(); })
            .UseServiceProviderFactory(new AutofacServiceProviderFactory());//Step 1:容器替换

3.Startup类中配置加入控制器替换规则

 public void ConfigureServices(IServiceCollection services)
        {
            services.Replace(ServiceDescriptor.Transient()); //Step 2:在Startup 服务配置中加入控制器替换规则
            services.AddControllers();
        }

4.定义特性标注


    /// 
    /// 依赖注入特性
    /// 
    public class DependencyRegisterAttribute : Attribute
    {

    }

    //添加特性标注
    [DependencyRegister]
    pu

你可能感兴趣的:(ASP.NET,Core)