net core3.1版本在mvc、webapi和控制台程序中使用autofac
一、mvc和webapi使用autofac如下:
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如下:
1、安装Autofac包,如上所述。
2、代码如下:
class Program { private static ITestRepository testRepository; static void Main(string[] args) { //builder var builder = new ContainerBuilder(); //单个注册 builder.RegisterType<TestRepository>().As<ITestRepository>(); //容器实例 IContainer instance = builder.Build(); //仓库实例 testRepository = instance.Resolve<ITestRepository>(); var str = testRepository.MyTest(); Console.WriteLine(str); Console.ReadKey(); } }