Autofac 整合asp.net core6
2022/6/20 1:21:56
本文主要是介绍Autofac 整合asp.net core6,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
1、Nuget引入
Autofac、Autofac.Extensions.DependencyInjection
2、Program.cs里面添加注入配置
{ //第一种方式注入 builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory()); //通过工厂替换,把Autofac整合进来 builder.Host.ConfigureContainer<ContainerBuilder>(option => { option.RegisterType<Microphone>().As<IMicrophone>(); option.RegisterType<Power>().As<IPower>(); option.RegisterType<Headphone>().As<Headphone>(); option.RegisterType<Headphone>().As<IHeadphone>(); }); ////第二种方式 //builder.Host //.UseServiceProviderFactory(new AutofacServiceProviderFactory()) //.ConfigureContainer<ContainerBuilder>(builder => //{ // builder.RegisterModule(new AutofacModuleRegister()); //}); }
第二种方式,是新建一个AutofacModuleRegister类
1 using Autofac; 2 using Business.IServices; 3 using Business.Services; 4 using System.Reflection; 5 6 namespace ProjectIOC.Extensions 7 { 8 public class AutofacModuleRegister : Autofac.Module 9 { 10 /// <summary> 11 /// 重新Autofac管道load方法,在这里注册注入 12 /// </summary> 13 /// <param name="builder"></param> 14 protected override void Load(ContainerBuilder builder) 15 { 16 //程序集 17 var IAppServices = Assembly.Load("Business.IServices"); 18 var AppServices = Assembly.Load("Business.Services"); 19 20 //根据名称约定(服务层的接口和实现均以Service结尾),实现服务接口和服务实现的依赖 21 builder.RegisterAssemblyTypes(IAppServices, AppServices) 22 .Where(t => t.Name.EndsWith("Service")) 23 .AsImplementedInterfaces(); 24 25 builder.RegisterType<Microphone>().As<IMicrophone>().SingleInstance(); 26 } 27 } 28 }View Code
在类里面添加注入
3、接下来就可以在控制器的构造函数里面添加依赖注入
1 using Autofac; 2 using Business.IServices; 3 using Microsoft.AspNetCore.Mvc; 4 5 namespace ProjectIOC.Controllers 6 { 7 public class HomeController : Controller 8 { 9 private readonly IMicrophone _microphone; 10 private readonly IMicrophone _microphone2; 11 private readonly IMicrophone _microphone3; 12 13 public HomeController(IMicrophone microphone,IServiceProvider serviceProvider,IComponentContext componentContext) 14 { 15 this._microphone = microphone; 16 this._microphone2 = serviceProvider.GetService<IMicrophone>(); 17 this._microphone3 = componentContext.Resolve<IMicrophone>(); 18 } 19 20 public IActionResult Index() 21 { 22 return View(); 23 } 24 } 25 }View Code
这篇关于Autofac 整合asp.net core6的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2022-03-01沐雪多租宝商城源码从.NetCore3.1升级到.Net6的步骤
- 2024-12-06使用Microsoft.Extensions.AI在.NET中生成嵌入向量
- 2024-11-18微软研究:RAG系统的四个层次提升理解与回答能力
- 2024-11-15C#中怎么从PEM格式的证书中提取公钥?-icode9专业技术文章分享
- 2024-11-14云架构设计——如何用diagrams.net绘制专业的AWS架构图?
- 2024-05-08首个适配Visual Studio平台的国产智能编程助手CodeGeeX正式上线!C#程序员必备效率神器!
- 2024-03-30C#设计模式之十六迭代器模式(Iterator Pattern)【行为型】
- 2024-03-29c# datetime tryparse
- 2024-02-21list find index c#
- 2024-01-24convert toint32 c#