其他分享
首页 > 其他分享> > net core3.1版本中使用autofac

net core3.1版本中使用autofac

作者:互联网

mvc和webapi通用。

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();
        }
 }

 

  

标签:autofac,containerBuilder,string,void,args,testRepository,core3.1,net,public
来源: https://www.cnblogs.com/qk2014/p/14270933.html