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();
        }
    });
}
相关推荐
lalala_Zou8 小时前
场景题:电商平台订单未支付过期如何实现自动关闭订单?
wpf
czhc11400756638 小时前
wpf 16
wpf
cn_mengbei1 天前
鸿蒙PC原生应用开发实战:ArkTS与DevEco Studio从零构建跨端桌面应用全栈指南
华为·wpf·harmonyos
lingxiao168881 天前
WebApi详解+Unity注入--上篇:基于Framework的WebApi
c#·wpf·web
是一个Bug1 天前
Java后端开发面试题清单(50道) - 分布式基础
java·分布式·wpf
无心水1 天前
【分布式利器:腾讯TSF】4、TSF配置中心深度解析:微服务动态配置的终极解决方案
分布式·微服务·架构·wpf·分布式利器·腾讯tsf·分布式利器:腾讯tsf
lingxiao168882 天前
WebApi详解+Unity注入--下篇:Unity注入
unity·c#·wpf
无心水2 天前
【分布式利器:腾讯TSF】6、TSF可观测性体系建设实战:Java全链路Metrics+Tracing+Logging落地
java·分布式·架构·wpf·分布式利器·腾讯tsf·分布式利器:腾讯tsf
故事不长丨3 天前
C#字典(Dictionary)全面解析:从基础用法到实战优化
开发语言·c#·wpf·哈希算法·字典·dictionary·键值对
冰茶_3 天前
WPF路由事件:隧道与冒泡机制解析
学习·c#·.net·wpf·.netcore·mvvm