Net Core教程

Autofac 整合asp.net core6

本文主要是介绍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的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!