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();
        }
    });
}
相关推荐
User_芊芊君子2 小时前
【分布式训练】CANN SHMEM跨设备内存通信库:构建高效多机多卡训练的关键组件
分布式·深度学习·神经网络·wpf
就是有点傻1 天前
WPF按钮走马灯效果
wpf
zuozewei1 天前
虚拟电厂聚合商平台安全技术体系深度解读
安全·wpf
极客智造1 天前
WPF 自定义控件:AutoGrid 实现灵活自动布局的网格控件
wpf
极客智造1 天前
WPF Grid 布局高效扩展:GridHelpers 附加属性工具类全解析
wpf
张人玉1 天前
WPF 多语言实现完整笔记(.NET 4.7.2)
笔记·.net·wpf·多语言实现·多语言适配
暖馒1 天前
深度剖析串口通讯(232/485)
开发语言·c#·wpf·智能硬件
我要打打代码2 天前
WPF控件(2)
wpf
c#上位机2 天前
wpf之行为
c#·wpf
kylezhao20192 天前
深入浅出地理解 C# WPF 中的属性
hadoop·c#·wpf