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();
        }
    });
}
相关推荐
李高钢1 天前
开源控件库 HandyControl 介绍与简单实践:让 WPF 界面告别“上个世纪“
开源·wpf
旋生万物2 天前
【终极实战】用Python从零“生成“一个宇宙:螺旋干涉模型的代码实现
开发语言·前端·人工智能·react.js·php·wpf
Now喔2 天前
WPF画刷介绍
wpf
李高钢2 天前
WPF/WinForms 客户端通过 gRPC 与后端通信:从 Proto 契约到流式调用的完整指南
wpf·grpc·winforms
一见已难忘3 天前
基于 Harmony 6.0 应用的宠物寄养预约系统实现
wpf·宠物
fl1768313 天前
基于C#WPF实现的内存加速球清理类似360加速球内存清理
开发语言·c#·wpf
李高钢3 天前
【WPF】高级 UI 与性能优化实战:从卡顿到丝滑
ui·性能优化·wpf
Chris _data4 天前
WPF 上位机开发学习笔记 - 第四天
笔记·学习·wpf
李高钢4 天前
除了 IDE,C#/WPF 开发者每天离不开的 10 个工具
ide·c#·wpf
李高钢4 天前
用 JetBrains Rider 写 WPF 的 15 个高效技巧:从 VS 转过来也值得看
wpf