最近新建了一个.net 6的core项目,长时间没有更新技术栈的我在刚使用的时候着实吃了一惊,Program.cs写法大变样了,具体的去看官方文档。这里说下在.net 6环境下的.net core项目里如何使用Autofac实现依赖注入。

  通常的,我们把其他服务注入到Controller时,使用.net core自带的依赖注入即可,但是如果我们要实现自定义服务注册时,就要用到第三方IOC组件了。这里推荐Autofac。(别的我不知道也没用过,hh)。

  第一步,在Nuget引入Autofac、Autofac.Extensions.DependencyInjection这两个dll。

  第二步,定义Module,方便对注入服务进行管理:

  .net 6 中使用Autofac

using Autofac;
using System.Reflection;

namespace Infrastructure
{
    public class AutofacModuleRegister : Autofac.Module
    {
        //重写Autofac管道Load方法,在这里注册注入
        protected override void Load(ContainerBuilder builder)
        {
            //程序集注入业务服务
            var IAppServices = Assembly.Load("Application");
            var AppServices = Assembly.Load("Application");
            //根据名称约定(服务层的接口和实现均以Service结尾),实现服务接口和服务实现的依赖
            builder.RegisterAssemblyTypes(IAppServices, AppServices)
              .Where(t => t.Name.EndsWith("Service"))
              .AsImplementedInterfaces();
        } 
    }   
}
View Code

相关文章:

  • 2021-10-25
  • 2021-11-28
  • 2021-09-15
  • 2022-12-23
  • 2021-07-11
  • 2021-04-20
  • 2018-03-28
猜你喜欢
  • 2021-06-04
  • 2022-01-09
  • 2021-07-17
  • 2022-03-05
  • 2021-11-19
  • 2021-11-26
  • 2022-12-23
相关资源
相似解决方案