.net Core WebApi使用AutoFac
阅读原文时间:2023年07月10日阅读:1

1.在要添加的项目中选中 依赖项->右键->管理NuGet程序包(N)

2.在NuGet包管理器中输入Autofac,安装选中文件

3.在项目中找到Program.cs文件,添加如下代码

    public static IHostBuilder CreateHostBuilder(string\[\] args) =>  
        Host.CreateDefaultBuilder(args)  
            .ConfigureWebHostDefaults(webBuilder =>  
            {  
                webBuilder.UseStartup<Startup>();  
            })  
            // 添加依赖注入  
            .UseServiceProviderFactory(new AutofacServiceProviderFactory());

4.在项目中找到Startup.cs文件,添加如下代码

    /// <summary>  
    /// 依赖注入配置容器  
    /// </summary>  
    /// <param name="builder"></param>  
    public void ConfigureContainer(ContainerBuilder builder)  
    {  
        ////单个服务注入  
        //builder.RegisterType<OrderService>().As<IOrderService>();

        // 获取 Service.dll 程序集服务,并注册  
        var assemblysService = Assembly.LoadFrom(Path.Combine(AppContext.BaseDirectory, "NetCoreWebApi.Service.dll"));  
        // 获取 IService.dll 程序集服务,并注册  
        var assemblysIService = Assembly.LoadFrom(Path.Combine(AppContext.BaseDirectory, "NetCoreWebApi.IService.dll"));  
        builder.RegisterAssemblyTypes(assemblysService)  
               .AsImplementedInterfaces()  
               .InstancePerDependency().PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies);  
        builder.RegisterAssemblyTypes(assemblysIService)  
               .AsImplementedInterfaces()  
               .InstancePerDependency().PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies);  
    }

5.添加好依赖注入,就可以直接在项目中使用

    private readonly ISysRoleServices \_sysRoleServices;  
    public SysRoleController(ISysRoleServices sysRoleServices)  
    {  
        \_sysRoleServices = sysRoleServices;  
    }