net core3.1版本中使用autofac

mvc和webapi通用。

1、安装Autofac包,如下图:

net core3.1版本中使用autofac

 

2、Program类中添加如下代码(红色部分):

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()) //使用autofac依赖注入
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }

 

  

3、Startup类中

a、添加ConfigureContainer方法,如下(红色部分):

 

public class Startup
    {
        //autofac
        public void ConfigureContainer(ContainerBuilder containerBuilder)
        {
            string repositoryImplAssembly = "RepositoryImpl";//接口仓库实现层程序集
            string repositorySuffix = "Repository";//仓库后缀

            //单个注册
            //containerBuilder.RegisterType<GoodsRepository>().As<IGoodsRepository>();

            //批量注册Repository仓库(需要引用RepositoryImpl,不然这里读取不到)
            Assembly repositoryAssemblies = Assembly.Load(repositoryImplAssembly);
            containerBuilder.RegisterAssemblyTypes(repositoryAssemblies)
                .Where(w => w.Name.EndsWith(repositorySuffix, StringComparison.CurrentCultureIgnoreCase))//根据后缀筛选
                .Where(x => x.IsClass) //筛选类
                .AsImplementedInterfaces() //接口实现类
                .InstancePerLifetimeScope();//生命周期

        }
        
        public void ConfigureServices(IServiceCollection services)
        {
            ......

        }
        
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            ......
        }
    }

 

 

 

  

b、ConfigureServices方法中添加如下代码(蓝色部分):

//mvc
 services.AddControllersWithViews()
         .AddControllersAsServices();//依赖注入需要

 

  

4、controller中使用,如下:

public class HomeController : Controller
{
        private readonly ITestRepository testRepository;
        public HomeController(ITestRepository _testRepository)
        {
            testRepository = _testRepository;
        }

        public IActionResult Index()
        {
            string ss = testRepository.MyTest();

            return View();
        }
 }

 

  

上一篇:.net core 3.1 使用autofac注入(一)


下一篇:.NET Core 中依赖注入框架详解 Autofac