百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术文章 > 正文

Abp vNext 依赖注入(依赖注入setter注入)

ccwgpt 2025-04-08 12:27 29 浏览 0 评论

介绍

ABP的依赖注入系统是基于Microsoft的依赖注入扩展库(
Microsoft.Extensions.DependencyInjection nuget包)开发的。所以我们采用
dotnet自带的注入方式也是支持的

  • 由于ABP是一个模块化框架,因此每个模块都定义它自己的服务并在它自己的单独模块类中通过依赖注入进行注册.例:
public class BlogModule : AbpModule
{
    public override void ConfigureServices(ServiceConfigurationContext context)
    {
        //在此处注入依赖项
        // dotnet自带依赖注入方式也是支持的
        context.services.AddTransient
        context.services.AddScoped
        context.services.AddSingleton
    }
}

Autofac

Autofac 是.Net世界中最常用的依赖注入框架之一. 相比.Net Core标准的依赖注入库, 它提供了更多高级特性, 比如动态代理和属性注入.

集成

1.安装 Volo.Abp.Autofac nuget 包到你的项目 (对于一个多项目应用程序, 建议安装到可执行项目或者Web项目中.)
2.模块添加 AbpAutofacModule 依赖:

    [DependsOn(typeof(AbpAutofacModule))]
    public class MyModule : AbpModule
    {
        //...
    }
}

3.配置
AbpApplicationCreationOptions 用 Autofac 替换默认的依赖注入服务. 根据应用程序类型, 情况有所不同

  • ASP.NET Core 应用程序
public class Program
{
    public static int Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    internal static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup();
            })
            .UseAutofac(); //Integrate Autofac!
}
  • 控制台应用程序
namespace AbpConsoleDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var application = AbpApplicationFactory.Create(options =>
            {
                options.UseAutofac(); //Autofac integration
            }))
            {
                //...
            }
        }
    }
}

依照约定的注册

如果实现这些接口,则会自动将类注册到依赖注入:

  • ITransientDependency 注册为transient生命周期.
  • ISingletonDependency 注册为singleton生命周期.
  • IScopedDependency 注册为scoped生命周期.

默认特定类型

一些特定类型会默认注册到依赖注入.例子:

  • 模块类注册为singleton.
  • MVC控制器(继承Controller或AbpController)被注册为transient.
  • MVC页面模型(继承PageModel或AbpPageModel)被注册为transient.
  • MVC视图组件(继承ViewComponent或AbpViewComponent)被注册为transient.
  • 应用程序服务(实现IApplicationService接口或继承ApplicationService类)注册为transient.
  • 存储库(实现IRepository接口)注册为transient.
  • 域服务(实现IDomainService接口)注册为transient.

手动注册

在某些情况下,你可能需要向IServiceCollection手动注册服务,尤其是在需要使用自定义工厂方法或singleton实例时.在这种情况下,你可以像Microsoft文档描述的那样直接添加服务.

public class BlogModule : AbpModule
{
    public override void ConfigureServices(ServiceConfigurationContext context)
    {
        context.services.AddTransient();
    }
}

如何使用

构造函数注入

  • 构造方法注入是将依赖项注入类的首选方式

属性注入

  • Microsoft依赖注入库不支持属性注入.但是,ABP可以与第三方DI提供商(例如Autofac)集成,以实现属性注入。
  • 属性注入依赖项通常被视为可选依赖项.这意味着没有它们,服务也可以正常工作.Logger就是这样的依赖项,MyService可以继续工作而无需日志记录.
public class MyService : ITransientDependency
{
    public ILogger Logger { get; set; }

    public MyService()
    {
        Logger = NullLogger.Instance;
    }

    public void DoSomething()
    {
        //...使用 Logger 写日志...
    }
}

IServiceProvider

直接从IServiceProvider解析服务.在这种情况下,你可以将IServiceProvider注入到你的类并使用

public class MyService : ITransientDependency
{
    private readonly IServiceProvider _serviceProvider;

    public MyService(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;
    }

    public void DoSomething()
    {
        var taxCalculator = _serviceProvider.GetService();
        //...
    }
}

服务替换

在某些情况下,需要替换某些接口的实现.

  • ITestManager有一个默认实现DefaultManager,但是我现在想替换成TestReplaceManager,该如何操作呢?

原生dotnet方式替换

services.Replace(ServiceDescriptor.Transient());

Abp支持

  • 加上Dependency特性标签
  • 加上ExposeServices特性标签
[Dependency(ReplaceServices = true)]
[ExposeServices(typeof(ITestManager))]
public class TestReplaceManager : ITestManager, ITransientDependency
{
	public void Print()
	{
		Console.WriteLine("TestReplaceManager");
	}
}

问题

  1. 有时候我们实现了ITransientDependency,ISingletonDependency,IScopedDependency但是再运行是还是提示依赖注入失败?
  • 实现类的名称拼写错误
  • 比如接口名称为ITestAppService,但是实现类为DefaultTessAppService,这个时候编译不会报错,但是运行报错,下面会基于源码分析。
public class DefaultTessAppService : ApplicationService, ITestAppService
{
   // ....
}
  1. 我通过[Dependency(ReplaceServices = true)]替换服务没有生效?
  • 请添加[ExposeServices(typeof(ITestManager))]显示暴露服务,下面会基于源码分析。

源码分析

  1. 进入到Startup.AddApplication源码
public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddApplication();
    }
}
  1. 进入到await app.ConfigureServicesAsync()源码
public async static Task CreateAsync(
    [NotNull] Type startupModuleType,
    [NotNull] IServiceCollection services,
    Action? optionsAction = null)
{
    var app = new AbpApplicationWithExternalServiceProvider(startupModuleType, services, options =>
    {
        options.SkipConfigureServices = true;
        optionsAction?.Invoke(options);
    });

    await app.ConfigureServicesAsync();
    return app;
}
  1. 主要查看ConfigureServices下的Services.AddAssembly(assembly)方法。
 public virtual async Task ConfigureServicesAsync()
    {
        
        // 省略...

        var assemblies = new HashSet();

        //ConfigureServices
        foreach (var module in Modules)
        {
            if (module.Instance is AbpModule abpModule)
            {
                if (!abpModule.SkipAutoServiceRegistration)
                {
                    var assembly = module.Type.Assembly;
                    if (!assemblies.Contains(assembly))
                    {
                        Services.AddAssembly(assembly);
                        assemblies.Add(assembly);
                    }
                }
            }

            try
            {
                await module.Instance.ConfigureServicesAsync(context);
            }
            catch (Exception ex)
            {
                throw new AbpInitializationException($"An error occurred during {nameof(IAbpModule.ConfigureServicesAsync)} phase of the module {module.Type.AssemblyQualifiedName}. See the inner exception for details.", ex);
            }
        }

        // 省略...
    }

4.进入下面AddAssembly下AddType的逻辑

public class DefaultConventionalRegistrar : ConventionalRegistrarBase
{
    public override void AddType(IServiceCollection services, Type type)
    {
        if (IsConventionalRegistrationDisabled(type))
        {
            return;
        }
        // 查看是否有DependencyAttribute特性标签
        var dependencyAttribute = GetDependencyAttributeOrNull(type);
        // 判断是否有实现接口,注入对于的类型。
        var lifeTime = GetLifeTimeOrNull(type, dependencyAttribute);

        if (lifeTime == null)
        {
            return;
        }

        var exposedServiceTypes = GetExposedServiceTypes(type);

        TriggerServiceExposing(services, type, exposedServiceTypes);

        foreach (var exposedServiceType in exposedServiceTypes)
        {
            var serviceDescriptor = CreateServiceDescriptor(
                type,
                exposedServiceType,
                exposedServiceTypes,
                lifeTime.Value
            );

            if (dependencyAttribute?.ReplaceServices == true)
            {
                services.Replace(serviceDescriptor);
            }
            else if (dependencyAttribute?.TryRegister == true)
            {
                services.TryAdd(serviceDescriptor);
            }
            else
            {
                services.Add(serviceDescriptor);
            }
        }
    }
}

    // GetLifeTimeOrNull

    protected virtual ServiceLifetime? GetLifeTimeOrNull(Type type, DependencyAttribute? dependencyAttribute)
    {
        return dependencyAttribute?.Lifetime ?? GetServiceLifetimeFromClassHierarchy(type) ?? GetDefaultLifeTimeOrNull(type);
    }
    // abp 三个生命周期
    protected virtual ServiceLifetime? GetServiceLifetimeFromClassHierarchy(Type type)
    {
        if (typeof(ITransientDependency).GetTypeInfo().IsAssignableFrom(type))
        {
            return ServiceLifetime.Transient;
        }

        if (typeof(ISingletonDependency).GetTypeInfo().IsAssignableFrom(type))
        {
            return ServiceLifetime.Singleton;
        }

        if (typeof(IScopedDependency).GetTypeInfo().IsAssignableFrom(type))
        {
            return ServiceLifetime.Scoped;
        }

        return null;
    }

5.重点到了,看下为什么名称错误为什么导致注入失败。

  • 通过接口的名称去获取实现。
  • 也能解释有时候不显示指定ExposeServices可能替换失败的问题
public class ExposeServicesAttribute : Attribute, IExposedServiceTypesProvider
{
    // 省略...

    private static List GetDefaultServices(Type type)
    {
        var serviceTypes = new List();

        foreach (var interfaceType in type.GetTypeInfo().GetInterfaces())
        {
            var interfaceName = interfaceType.Name;
            if (interfaceType.IsGenericType)
            {
                interfaceName = interfaceType.Name.Left(interfaceType.Name.IndexOf('`'));
            }

            // 查询到实现类的名称是否是移除I
            if (interfaceName.StartsWith("I"))
            {
                interfaceName = interfaceName.Right(interfaceName.Length - 1);
            }
            // 查询到实现类的名称是否以接口名结尾
            if (type.Name.EndsWith(interfaceName))
            {
                serviceTypes.Add(interfaceType);
            }
        }

        return serviceTypes;
    }
}

相关推荐

公司组织架构及部门职责#管理制度 #薪酬绩效 #组织架构

...

终于把“公司组织架构与管理部岗位配置”整理好了,拿来即用!

...

老板看完这份“公司组织架构详解”就解放了!

...

丨公司丨公司大架构整理汇总

注:本文转自团队成员原创作品,特此鸣谢(公号:法海图鉴)今日话题公司大架构整理背景介绍经过前几期话题对各种企业类型的介绍,想必大家已经有了初步认识。之后我将带着大家开启对公司的深入了解。本期...

图解物理--八年级物理下册最全知识框架导图

第七章力1力2弹力3重力第八章运动和力1牛顿第一定律2二力平衡3摩擦力第九章压强1压强2液体压强3大气压强4流体压强与流速的关系第十章浮力1浮力2阿基米德原理3物体的浮沉条件及应用第十一章功...

八年级上册生物,思维导图,期末高分必备资料,家长收藏

这是八年级上册生物的思维导图,孩子在背诵知识点的时候,可以看一下知识点在导图中的位置,形成对知识点整体的把握,有助于学生拿高分,特别是图片中带红色星星的部分,更是要注意背诵,是重点内容。家长可以把图片...

2019政府工作报告精华,这张思维导图里全都有

每经记者:李可愚每经编辑:陈星每日经济新闻

图解薪酬体系结构设计

...

司考复习独家总结!一张图总结行政法知识结构体系

作为三大实体法之一,行政法的分值在60分左右,行政法在司法考试中一直比较平稳常规,没有偏题怪题,还是比较容易得分的。小编要提醒大家,在3月之前要把三大实体法学习一遍。下图是厚大在线360导学师小周总结...

一图读懂香港国安新架构:各职位人选公布 有官员曾强硬喊话乱港分子

实用干货!高中物理框架图,让零碎知识“串联”起来

高中物理学习一定要抓好逻辑结构大框架!了解整个知识框架体系后,更易抓住骨干知识,干掉重难知识点~今天给大家分享高中物理的框架图同学们赶紧收藏起来吧!力学知识结构图光学知识结构图热学、原子物理知识结构图...

254m超高层办公楼型钢砼框架-核心筒结构图

高度类别:超高层建筑钢筋混凝土结构:框架,框架核心筒钢结构:钢框架建筑功能:办公包含:办公楼57层(-3层)254.150m钻孔灌注桩桩+筏板型钢混凝土框架-钢筋混凝土核心筒西裙房2层(-...

砖混结构与框架结构,究竟有何区别?千万别被坑!

现在买房装修的人最怕啥?不是价格高,而是房子不安全!两种主流建筑结构,砖混靠墙,框架靠柱子,选错了隔墙都可能要命。简单说,砖混便宜但别碰高层,框架贵点但能保命。砖混那些承重墙根本不能拆,想砸墙改个开放...

大师一百——高中化学必考:《元素周期律》考点框架图

今天大师给大家带来的是高中化学的《元素周期律》考点框架图,高中的同学必须牢记于心,这种重要的考点,考试是一定会考的!化学大师...

需求分析框架图

需求分析框架图

取消回复欢迎 发表评论: