一个非常简单的入门级ASP.NET Core Autofac使用
2020-10-22 16:12 金金金金金 阅读(275) 评论(1) 编辑 收藏 举报好好学习,天天向上。
这是结构。
方法一 在Program中,添加Autofac服务
1:
1 public static void Main(string[] args) 2 { 3 CreateHostBuilder(args).Build().Run(); 4 } 5 // public static IHostBuilder CreateHostBuilder(string[] args) => 6 //Host.CreateDefaultBuilder(args) 7 // .ConfigureWebHostDefaults(webBuilder => 8 // { 9 // webBuilder.UseStartup<Startup>(); 10 // }).UseServiceProviderFactory(new AutofacServiceProviderFactory()); 11 public static IHostBuilder CreateHostBuilder(string[] args) => 12 Host.CreateDefaultBuilder(args) 13 .UseServiceProviderFactory(new AutofacServiceProviderFactory())//添加Autofac服务 14 .ConfigureWebHostDefaults(webBuilder => 15 { 16 webBuilder.UseStartup<Startup>(); 17 });
2: Startup类修改ConfigureContainer方法
1 public void ConfigureContainer(ContainerBuilder builder) 2 { 3 builder.RegisterType<OneService>().As<IOneService>(); 4 }
方法二, 继承module
1. 创建CustomAutofacModule 类
1 public class CustomAutofacModule :Autofac.Module 2 { 3 /// <summary> 4 /// AutoFac注册类 5 /// </summary> 6 /// <param name="builder"></param> 7 protected override void Load(ContainerBuilder builder) 8 { 9 /*单次注入*/ 10 builder.RegisterType<OneService>().As<IService>(); 11 14 } 15 24 }
2: Startup类修改ConfigureContainer方法
public void ConfigureContainer(ContainerBuilder builder) { // 直接用Autofac注册我们自定义的 // builder.RegisterModule(new CustomAutofacModule()); }
批量注入
修改CustomAutofacModule 类
1 public class CustomAutofacModule :Autofac.Module 2 { 3 /// <summary> 4 /// AutoFac注册类 5 /// </summary> 6 /// <param name="builder"></param> 7 protected override void Load(ContainerBuilder builder) 8 { 9 ///*单次注入*/ 10 //builder.RegisterType<OneService>().As<IService>(); 11 //注册Service中的对象,Service中的类要以Service结尾,否则注册失败 12 builder.RegisterAssemblyTypes(GetAssemblyByName("Services")). 13 Where(a => a.Name.EndsWith("Service")).AsImplementedInterfaces(); 14 } 15 /// <summary> 16 /// 根据程序集名称获取程序集 17 /// </summary> 18 /// <param name="AssemblyName">程序集名称</param> 19 /// <returns></returns> 20 public static Assembly GetAssemblyByName(String AssemblyName) 21 { 22 return Assembly.Load(AssemblyName); 23 } 24 }
之后再控制器注入调用一下就好(接口方法就自己去随便定义一下了,这只是一个初级入门。)
1 public class HomeController : Controller 2 { 3 private readonly ILogger<HomeController> _logger; 4 private readonly IOneService _server; 5 private readonly IArticleService _articleService; 6 7 public HomeController(ILogger<HomeController> logger, IOneService service, IArticleService articleService) 8 { 9 _logger = logger; 10 _server = service; 11 _articleService = articleService; 12 } 13 14 public IActionResult Index() 15 { 16 string a = _server.SayHi(); 17 string b = _articleService.article(); 18 return View(); 19 } 20 21 22 }
不知道如何深入学习, 有哪位能够指点一下学习道路。感激不尽