首页 > 其他分享 >Spectre.Console.Cli注入服务的几种姿势

Spectre.Console.Cli注入服务的几种姿势

时间:2024-07-24 18:18:20浏览次数:7  
标签:Console Cli settings class Spectre var services config public

Spectre.Console大家可能都不陌生,写控制台程序美化还是不错的,支持着色,表格,图标等相当nice,如果对这个库不熟悉我强烈推荐你了解一下,对于写一些CLI小工具还是相当方便的, 本文主要讲讲 Spectre.Console.Cli的服务注入, TA是 Spectre.Console 库的一部分,用于创建命令行界面(CLI)应用程序。它提供了一个强大且易于使用的API来定义命令、参数和选项,同时支持 Spectre.Console 的丰富输出格式化功能。

一个官方极简的例子,定义一个GreetCommand:

public class GreetCommand : Command<GreetCommand.Settings>
{
    public class Settings : CommandSettings
    {
        [CommandArgument(0, "<name>")]
        [Description("The name of the person to greet.")]
        public string Name { get; set; }

        [CommandOption("-r|--repeat <times>")]
        [Description("The number of times to repeat the greeting.")]
        [DefaultValue(1)]
        public int Repeat { get; set; }
    }
    public override int Execute(CommandContext context, Settings settings)
    {
        for (int i = 0; i < settings.Repeat; i++)
        {
            Console.WriteLine($"Hello, {settings.Name}!");
        }
        return 0;
    }
}

接下来,在程序的入口点配置Command

public class Program
{
    public static int Main(string[] args)
    {
        var app = new CommandApp();
        app.Configure(config =>
        {
            config.AddCommand<GreetCommand>("greet");
        });
        return app.Run(args);
    }
}

对于Spectre.Console.Cli的常规使用我这里不做过多介绍,感兴趣的同学可以移步官方文档,本文主要讲一下在CLI程序中如何注入服务

那么我们需要在GreetCommand中注入服务应该怎么做呢? 比如下面的一个服务:

public class HelloService(ILogger<HelloService> logger)
{
    public Task<string> SayHello(string name, int age)
    {
        //注入的logger
        logger.LogInformation("SayHello called with name:{name},age:{age}", name, age);
        return Task.FromResult($"Hello,My name is {name}, I`m {age} years old!");
    }
}

其实Spectre.Console.Cli内置了最简单的方式,我们只需要在app.Configure中完成:

var services = new ServiceCollection();
//添加服务
services.AddSingleton<HelloService>();
//添加日志
services.AddLogging(config =>
{
    config.AddConsole();
});
var sp = services.BuildServiceProvider();

app.Configure(config =>
{
    //添加Commands
    config.AddCommand<OneCommand>("one");
    config.AddCommand<AnotherCommand>("another");
    //注册Services
    config.Settings.Registrar.RegisterInstance(sp.GetRequiredService<HelloService>());
});

注册的服务就可以直接使用了:

public class HelloCommand(HelloService helloService) : AsyncCommand<HelloCommand.HelloSettings>
{
    private readonly HelloService _helloService = helloService;
    public class HelloSettings : CommandSettings
    {
        [CommandArgument(0, "<name>")]
        [Description("The target to say hello to.")]
        public string Name { get; set; } = null!;
    }
    public override async Task<int> ExecuteAsync(CommandContext context, HelloSettings settings)
    {
        var message = await _helloService.SayHello(settings.Name, settings.Age);
        AnsiConsole.MarkupLine($"[blue]{message}[/]");
        return 0;
    }
}

另外的一个注入方式是实现ITypeRegistrar,官方提供MSDI的用例,自己也可以实现Autofac等其他DI,下面是MSDI的实现:

namespace Infrastructure
{
    public sealed class MsDITypeRegistrar(IServiceCollection services) : ITypeRegistrar
    {
        private readonly IServiceCollection _services =
            services ?? throw new ArgumentNullException(nameof(services));
        public ITypeResolver Build()
        {
            return new TypeResolver(_services.BuildServiceProvider());
        }
        public void Register(Type service, Type implementation)
        {
            _services.AddSingleton(service, implementation);
        }
        public void RegisterInstance(Type service, object implementation)
        {
            _services.AddSingleton(service, implementation);
        }
        public void RegisterLazy(Type service, Func<object> factory)
        {
            _services.AddSingleton(service, (provider) => factory());
        }
    }
    internal sealed class TypeResolver(IServiceProvider provider) : ITypeResolver
    {
        public object? Resolve(Type? type)
        {
            if (provider is null || type is null)
            {
                return null;
            }
            return ActivatorUtilities.GetServiceOrCreateInstance(provider, type);
        }
    }
}

使用的话只需要实例化CommandApp时候传入MsDITypeRegistrar即可:

var services = new ServiceCollection();
//添加服务...

var app = new CommandApp(new MsDITypeRegistrar(services));
app.Configure(config =>
{
   //...
});
return app.Run(args);

除了上面的方式,我们其实还可以使用ICommandInterceptor切面的方式来完成注入的操作:

下面我们定义一个AutoDIAttribute特性,实现一个AutoDIInterceptor的拦截器,后者主要给标记了AutoDI的属性服务赋值

[AttributeUsage(AttributeTargets.Property, Inherited = true)]
public class AutoDIAttribute : Attribute{ }

/// <summary>
/// 自动注入的拦截器
/// </summary>
internal class AutoDIInterceptor(IServiceProvider serviceProvider) : ICommandInterceptor
{
    public void Intercept(CommandContext context, CommandSettings settings)
    {
        var type = settings.GetType();
        var properties = type.GetProperties();
        foreach (var property in properties)
        {
            var isAutoInject = property.GetCustomAttributes<AutoDIAttribute>(true).Any();
            if (isAutoInject)
            {
                var service = ActivatorUtilities.GetServiceOrCreateInstance(serviceProvider, property.PropertyType);
                property.SetValue(settings, service);
            }
        }
    }
}

接下来在CommandSettings中标记需要自动注入服务的属性,如下面的HelloService:

internal class AutoDICommand : AsyncCommand<AutoDICommand.AnotherInjectSettings>
{
    public class AnotherInjectSettings : CommandSettings
    {
        /// <summary>
        /// 使用切面装载的服务
        /// </summary>
        [AutoDI]
        public HelloService HelloService { get; set; } = null!;

        [Description("user name")]
        [DefaultValue("vipwan"), CommandOption("-n|--name")]
        public string Name { get; set; } = null!;

        [Description("user age")]
        [DefaultValue(12), CommandOption("-a|--age")]
        public int Age { get; set; }
    }

    public override async Task<int> ExecuteAsync(CommandContext context, AnotherInjectSettings settings)
    {
        var message = await settings.HelloService.SayHello(settings.Name, settings.Age);
        AnsiConsole.MarkupLine($"[green]{message}[/]");
        return 0;
    }
}

然后在app.Configure中使用AutoDIInterceptor切面:

var services = new ServiceCollection();
//添加服务
services.AddSingleton<HelloService>();
var sp = services.BuildServiceProvider();

app.Configure(config =>
{
    //设置自动注入的拦截器
    config.SetInterceptor(new AutoDIInterceptor(sp));
    config.AddCommand<AutoDICommand>("di");
    //...
});

然后测试运行程序:

dotnet run -- di -n "vipwan"

大功告成:
24.cnblogs.com/blog/127598/202407/127598-20240724180421239-1298412615.png)

以上就介绍了几种在Spectre.Console.Cli注入服务的方式,当然没有最优的只有最适合自己的,如果代码存在不足,或者你有更好的建议 欢迎留言交流!

标签:Console,Cli,settings,class,Spectre,var,services,config,public
From: https://www.cnblogs.com/vipwan/p/18321432

相关文章

  • CLIP-DIY 论文解读:基于 CLIP 和无监督目标定位的语义分割
    CLIP-DIY是一种基于CLIP模型的开放词汇语义分割方法,特点是无需额外的训练或者像素级标注,即可实现高效、准确的分割效果。该方法主要利用CLIP模型在图像分类方面的强大能力,并结合无监督目标定位技术,实现开放词汇语义分割。在论文中,首先肯定了CLIP出现的重要意义,开启了开放......
  • 在 Katana CLI 批处理中将发现的 URL 映射到原始 URL 时出现问题
    我使用KatanaCLI进行网络爬行,并使用Python包装器来管理批处理和输出解析。我的目标是将所有发现的URL映射回其原始URL,但我面临着一些发现的URL无法正确映射的问题,特别是当域相似或涉及子域时。以下是我的设置:|||输入:powerui.f​​oo.com、acnmll-en.foo.co......
  • 用于自动访问 MongoDB Atlas CLI 的 Python 脚本
    我想编写一个Python脚本,以便普通用户可以访问他的数据库并从他的终端执行CRUD操作。我正在查看官方文档,但我有点迷失。有人可以给我指点基本教程来开始吗?当然,以下是如何构建Python脚本来访问MongoDBAtlasCLI的基本教程:先决条件:MongoDBAtlas......
  • CF521E Cycling City 题解
    Description给定一张\(n\)个点\(m\)条边的无向简单图。问图中能否找到两个点,满足这两个点之间有至少三条完全不相交的简单路径。\(n,m\le2\times10^5\),图不保证连通。Solution容易发现有解地充要条件是存在两个环有边交,考虑在dfs树上做这件事。注意到非树边一定......
  • HttpClient 发送get和post请求的使用方法
    一Httpclient的简介    HttpClient是ApacheJakartaCommon下的子项目,可以用来提供高效的,最新的,功能丰富的支持HTTP协议的客户端变成工具包,并且他支持HTTP协议最新的版本和建议。核心API:HttpClient  HttpClientsCloseableHttpClientHttpGetHttpPost二Ht......
  • eclipse如何写python程序
    本文主要介绍在Windows系统环境下,搭建能在Eclipse中运行python程序的环境。一、Eclipse下载与安装:Eclipse是写JAVA的IDE,下载地址为:http://www.eclipse.org/downloads/下载安装,网上教程很多,不赘述。二、pydev插件下载与安装:启动Eclipse,点击Help—>EclipseMarketplace......
  • pymobiledevice3:如果没有抽象方法“_create_service_connection”的实现,则无法实例化
    全面披露:我不知道我在做什么。我没有编程经验。我已要求ChatGPT为我创建一个程序。ChatGPT为我创建的文件之一名为“device_detection.py”。这个特定文件应该检测通过USB端口连接到我的笔记本电脑的智能手机设备,然后在终端中打印结果。如果这就是我所需要的,那就太好了(并且......
  • 为什么 exitonclick 在我的 Python Turtle 图形程序中不起作用?
    我正在开发一个PythonTurtle图形程序,我正在尝试使用exitonclick方法在单击窗口时关闭窗口。但是,它似乎不起作用。fromturtleimportTurtle,Screenrem=Turtle()screen=Screen()rem.fd(70)defclear():screen.clearscreen()screen.listen()s......
  • HttpClient用法
    HttpClient是ApacheJakartaCommon下的子项目,可以用来提供最新的,高效的,功能丰富的支持Http协议的客户端编程工具包,它支持HTTP最新的版本和协议,通过HTTPClient就可以构造Http请求并发送Http请求核心API:HttpClientHttpClientsCloseableHttpClientHttpGetHpptPost发送请......
  • Spring Book Club + java查询数据库 + 百万数据 + 同步Elasticsearch(ES)+ 多线程 + Fei
    @FeignClient(name="bwie-elastic")publicinterfaceEsFeign{@PostMapping("/add")publicResultadd(@RequestBodyArrayList<ResourceInfo>resourceInfo);}@RestControllerpublicclassUserControllerimplementsApplica......