.net core 3.1 autofac(webapi / mvc 通过)

之前在.net core 3.1 的webapi项目中使用过autofac框架,但是没做记录。考虑到vue的seo问题,所以觉得mvc项目还是有必要研究下的,在这分享下mvc下autofac的使用。

1、NuGet安装依赖包

Autofac
Autofac.Extensions.DependencyInjection

 2、配置

2.1 Startup.cs中重写ConfigureContainer方法

1 public void ConfigureContainer(ContainerBuilder builder)
2 {
3     builder.RegisterModule<AutofacRegister>();
4 }

其中AutofacRegister.cs如下

 1 using System.IO;
 2 using System.Linq;
 3 using System.Reflection;
 4 
 5 namespace Y.MVC
 6 {
 7     /// <summary>
 8     /// autofac配置类
 9     /// </summary>
10     public class AutofacRegister : Autofac.Module
11     {
12         protected override void Load(ContainerBuilder builder)
13         {
14             #region 
15             var basePath = Microsoft.DotNet.PlatformAbstractions.ApplicationEnvironment.ApplicationBasePath;//获取项目路径
16             var servicesDllFile = Path.Combine(basePath, "Y.MVC.Service.dll");//获取注入项目绝对路径
17             var assemblysServices = Assembly.LoadFile(servicesDllFile);//直接采用加载文件的方法
18             builder.RegisterAssemblyTypes(assemblysServices).AsImplementedInterfaces();
19 
20             var repositoryDllFile = Path.Combine(basePath, "Y.MVC.IService.dll");
21             var repositoryServices = Assembly.LoadFile(repositoryDllFile);//直接采用加载文件的方法
22             builder.RegisterAssemblyTypes(repositoryServices).AsImplementedInterfaces();
23             #endregion
24 
25             #region 
26             var controllersTypesInAssembly = typeof(Startup).Assembly.GetExportedTypes()
27             .Where(type => typeof(Microsoft.AspNetCore.Mvc.ControllerBase).IsAssignableFrom(type)).ToArray();
28             builder.RegisterTypes(controllersTypesInAssembly).PropertiesAutowired();
29             #endregion
30         }
31     }
32 }

这里要说一下,我看了网上很多很多的教程,很多都是挨个服务类加载,我这个是通过DLL加载整个程序集中的接口类,但是会有解耦的问题,如果发生解耦问题,要重新生成下DLL(确定bin下包含要注入的服务类的程序集)。然后我这边推荐使用属性注入,构造函数注入本身并不复杂,但是再加上日志等杂七杂八的,会导致构造函数过于庞大。

2.2 Program.cs中修改CreateHostBuilder方法

.UseServiceProviderFactory(new AutofacServiceProviderFactory())

然后这块重点说一下哈,一定要注意这段代码的位置!除此之外,还需要修改一个地方,ConfigureServices方法

3、Controller中使用

 这就没啥说的了,属性注入成功,直接使用就行了,注意下声明的使用需要public。

原文地址:https://www.cnblogs.com/PrintY/p/13662837.html