wpf prism DryIoc批量注册服务

1.首先引入Scrutor包

2.在App.xaml.cs中注册

csharp 复制代码
protected override IContainerExtension CreateContainerExtension()
 {
     var serviceCollection = new ServiceCollection();
     serviceCollection.AddMemoryCache();
     serviceCollection.AddAutoMapper();
     serviceCollection.RegisteServices();
    
     return new DryIocContainerExtension(new Container(CreateContainerRules())
         .WithDependencyInjectionAdapter(serviceCollection));
 }

3.ServiceExtension类:

csharp 复制代码
public static void RegisteServices(this IServiceCollection services)
{
    services.Scan(scan =>
    {
        scan.FromAssemblyOf<GlobalValues>()
            .AddClasses(classes => classes.Where(t => t.Name.EndsWith("Service", StringComparison.OrdinalIgnoreCase)))
            .AsImplementedInterfaces()
            .WithScopedLifetime();
    });
}

如果没有一接口多实现的情况

这段代码就满足了

如果有一接口多实现的情况,需要额外加一部分代码

csharp 复制代码
public static void RegisteServices(this IServiceCollection services)
{
    var uploadWay = ConfigurationManager.AppSettings["UploadWay"];//自定义字段包含在命名的service中用来判断具体注册那个service

    services.Scan(scan =>
    {
        scan.FromAssemblyOf<GlobalValues>()
            .AddClasses(classes => classes.Where(t => t.Name.EndsWith("Service", StringComparison.OrdinalIgnoreCase)))
            .AsImplementedInterfaces()
            .WithScopedLifetime();

        if (!string.IsNullOrEmpty(uploadWay))
        {
            scan.FromAssemblyOf<GlobalValues>()
                      .AddClasses(classes => classes.Where(t =>
                        t.Name.EndsWith("Service", StringComparison.OrdinalIgnoreCase) &&
                        t.Name.Contains(uploadWay, StringComparison.OrdinalIgnoreCase)))
                      .AsImplementedInterfaces().WithScopedLifetime();
        }
    });
}
相关推荐
一水13 小时前
Redis实战:一个AI工作流系统里的五个应用场景,从传参到限流的完整链路
数据库·redis·wpf
dalong1016 小时前
WPF:3D甜甜圈
3d·c#·wpf·甜甜圈
别催小唐敲代码19 小时前
ROS2从入门到实战:去中心化机器人操作系统详解
wpf·ros2
脚踏实地皮皮晨2 天前
003006001_WrapPanel控件
开发语言·c#·.net·wpf·visual studio
脚踏实地皮皮晨2 天前
003005002_WPF StackPanel 基类官方类定义逐行深度解析
开发语言·windows·算法·c#·wpf·visual studio
脚踏实地皮皮晨2 天前
003004002_UniformGrid控件的使用方法
开发语言·c#·.net·wpf·visual studio
脚踏实地皮皮晨3 天前
003003002_WPF Grid 基类官方类定义逐行深度解析
开发语言·windows·算法·c#·wpf·visual studio
脚踏实地皮皮晨4 天前
003002004_WPF Panel 基类 官方类定义
开发语言·windows·算法·c#·wpf·visual studio
湿滑路面4 天前
Rouyan:使用WPF/C#构建的基于LLM的快捷翻译小工具
开发语言·c#·wpf
软萌萌的14 天前
C#中的多级缓存架构设计与实现深度解析
缓存·c#·wpf