前往小程序,Get更优阅读体验!
立即前往
发布
社区首页 >专栏 >面向 .NET 开发人员的 10 大NuGet 包:增强您的开发工具包

面向 .NET 开发人员的 10 大NuGet 包:增强您的开发工具包

作者头像
郑子铭
发布2024-11-23 13:29:36
发布2024-11-23 13:29:36
22100
代码可运行
举报
运行总次数:0
代码可运行

发现可以提升您的 .NET 开发工具包的前 10 个独家 NuGet 包!这些强大的软件包提供基本功能,简化您的工作流程,并增强您的编码体验。从用于改进数据处理的库到简化 API 集成的工具,每个软件包都旨在提高您作为开发人员的生产力和效率。立即深入了解此精选列表,为您的 .NET 项目解锁新功能!

面向 .NET 开发人员的 10 大独家 NuGet 软件包

当然!下面更深入地探讨了 .NET Core 开发中特定高级用例的更独特和高质量的 NuGet 包。这些软件包通常用于更专业、高性能或可扩展的应用程序和框架。

1. MassTransit

目的: 一个分布式应用程序框架,用于构建消息驱动型和事件驱动型微服务。

特征:

  • 可与 RabbitMQ、Azure Service Bus 和 Kafka 等常用消息代理配合使用。
  • 支持高级消息传递模式,如发布/订阅、请求/响应和路由滑。
  • 内置对重试、断路器和容错的支持。

非常适合构建大规模事件驱动型系统或微服务架构的开发人员。

NuGet 链接

在 .NET 中安装包:

代码语言:javascript
代码运行次数:0
复制
dotnet add package MassTransit --version 8.2.5

示例使用代码:

代码语言:javascript
代码运行次数:0
复制
//Create producer:  
using MassTransit;  
  
var busControl = Bus.Factory.CreateUsingRabbitMq(cfg =>  
{  
    cfg.Host("rabbitmq://localhost"); // Ensure RabbitMQ is running  
});  
  
await busControl.StartAsync();  
  
try  
{  
    // Send a message  
    var message = new MyMessage { Text = "Hello, MassTransit!" };  
    await busControl.Publish(message);  
    Console.WriteLine("Message sent: " + message.Text);  
}  
finally  
{  
    await busControl.StopAsync();  
}  
  
// Create Consumer :  
using MassTransit;  
using System;  
using System.Threading.Tasks;  
  
public class MyMessageConsumer : IConsumer\<MyMessage\>  
{  
    public Task Consume(ConsumeContext\<MyMessage> context)  
    {  
        Console.WriteLine("Message received: " + context.Message.Text);  
        return Task.CompletedTask;  
    }  
}  
  
// Program.cs:  
  
using MassTransit;  
  
var busControl = Bus.Factory.CreateUsingRabbitMq(cfg =>  
{  
    cfg.Host("rabbitmq://localhost");  
      
    cfg.ReceiveEndpoint("my-message-queue", e =>  
    {  
        e.Consumer\<MyMessageConsumer>();  
    });  
});  
  
await busControl.StartAsync();  
  
Console.WriteLine("Consumer is running. Press any key to exit.");  
Console.ReadKey();  
  
await busControl.StopAsync();

2. Rebus

目的: Rebus 是 MassTransit 的更简单、更精简的替代方案,它是一个适用于 .NET 的服务总线框架,有助于异步消息传递。

特征:

  • 重量轻,易于设置。
  • 支持各种消息代理,如 RabbitMQ、Azure Service Bus 和 Amazon SQS。
  • 非常适合消息驱动的分布式系统。

提供比 MassTransit 更轻量级的解决方案,适用于不需要繁重的消息传送基础设施的应用程序。

NuGet 链接

在 .NET 中安装包:

代码语言:javascript
代码运行次数:0
复制
dotnet add package Rebus --version 8.6.0

示例使用代码:

代码语言:javascript
代码运行次数:0
复制
var bus = new RebusBus(...);  
bus.Start(1); //< 1 worker thread  
  
// use the bus for the duration of the application lifetime  
  
// remember to dispose the bus when your application exits  
bus.Dispose();  

3. HotChocolate(适用于 .NET 的 GraphQL)

**目的:**适用于 .NET 的高性能 GraphQL 服务器实现。

特征:

  • 强类型 GraphQL 架构生成。
  • 高度可定制,支持订阅、分页和批处理等高级 GraphQL 功能。
  • 集成了对 ASP.NET Core 和依赖项注入的支持。

非常适合构建依赖 GraphQL 功能的可扩展、灵活的 API 的开发人员。

NuGet 链接

在 .NET 中安装包:

代码语言:javascript
代码运行次数:0
复制
dotnet add package HotChocolate --version 13.9.14

示例使用代码:

代码语言:javascript
代码运行次数:0
复制
using HotChocolate.AspNetCore;  
  
var builder = WebApplication.CreateBuilder(args);  
  
// Add HotChocolate services  
builder.Services.AddGraphQLServer()  
    .AddQueryType<Query>();  
  
var app = builder.Build();  
  
// Map GraphQL endpoint  
app.MapGraphQL("/graphql");  
  
app.Run();

4. Akka.NET

**目的:**一个分布式执行组件模型框架,用于构建高并发、分布式和容错系统。

特征:

  • 基于 Actor 的并发模型,有助于避免锁和争用条件。
  • 分布式和基于集群的 actor 系统。
  • 轻松处理事件驱动型高度分布式系统。

非常适合使用高并发实时系统(例如游戏、IoT 或金融应用程序)的开发人员。

NuGet 链接

在 .NET 中安装包:

代码语言:javascript
代码运行次数:0
复制
dotnet add package Akka --version 1.5.30

示例使用代码:

代码语言:javascript
代码运行次数:0
复制
using Akka.Actor;  
using System;  
  
public class GreetingActor : ReceiveActor  
{  
    public GreetingActor()  
    {  
        Receive<string>(message => HandleGreeting(message));  
    }  
  
    private void HandleGreeting(string message)  
    {  
        Console.WriteLine($"Received greeting: {message}");  
    }  
}  
  
// in program.cs  
using Akka.Actor;  
  
class Program  
{  
    static void Main(string[] args)  
    {  
        // Create the actor system  
        var system = ActorSystem.Create("GreetingSystem");  
  
        // Create the actor  
        var greetingActor = system.ActorOf<GreetingActor>("greetingActor");  
  
        // Send a message to the actor  
        greetingActor.Tell("Hello, Akka.NET!");  
  
        // Wait for user input before shutting down  
        Console.ReadLine();  
  
        // Terminate the actor system  
        system.Terminate().Wait();  
    }  
}  

5. Grpc.AspNetCore

目的: 支持在 .NET Core 中使用 gRPC 构建高性能远程过程调用 (RPC) 服务。

特征:

  • 通过 HTTP/2 进行高性能、低延迟的通信。
  • 通过 Protocol Buffers (protobuf) 的强类型合约。
  • 完全支持流式处理。

通常用于需要在微服务之间进行高效、实时通信的场景。

NuGet 链接

在 .NET 中安装包:

代码语言:javascript
代码运行次数:0
复制
dotnet add package Grpc.AspNetCore --version 2.66.0

示例使用代码:

代码语言:javascript
代码运行次数:0
复制
using GrpcGreeter.Services;  
  
var builder = WebApplication.CreateBuilder(args);  
  
// Add services to the container.  
builder.Services.AddGrpc();  
  
var app = builder.Build();  
  
// Configure the HTTP request pipeline.  
app.MapGrpcService<GreeterService>();  
  
app.Run();

6. Steeltoe.Common.Net

目的: 一组将云原生开发模式引入 .NET 的库,最初由 Pivotal 开发。

特征:

  • 与 Azure、Kubernetes 和 Cloud Foundry 等云平台集成。
  • 支持服务发现、分布式配置和微服务运行状况监控。
  • 内置断路器、重试和隔板策略(Polly 集成)。

对于构建面向云平台并需要高级可靠性模式的微服务的开发人员来说,这是必不可少的。

NuGet 链接

在 .NET 中安装包:

代码语言:javascript
代码运行次数:0
复制
dotnet add package Steeltoe.Common.Net --version 3.2.8

示例使用代码:

代码语言:javascript
代码运行次数:0
复制
{
  "spring": {
    "cloud": {
      "config": {
        "uri": "http://localhost:8888" // URL of your Spring Cloud Config server
      }
    }
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}
代码语言:javascript
代码运行次数:0
复制
[HttpGet]
        public IActionResult GetConfigValue()
        {
            // Fetch a configuration value from the Spring Cloud Config server
            var myValue = _configuration["MyConfigValue"]; // Replace with your config key
            return Ok(new { ConfigValue = myValue });
        }
代码语言:javascript
代码运行次数:0
复制
// Add Steeltoe configuration for Spring Cloud Config
builder.Configuration.AddConfigServer(); // This line enables Spring Cloud Config integration

7. Elsa

目的: 一个工作流库,用于在 .NET 中创建长时间运行的分布式工作流。

特征:

  • 通过 Fluent API、JSON 或图形设计器的声明式工作流。
  • 支持具有持久性的短期和长期运行的工作流。
  • 工作流版本控制、分支和活动。

非常适合构建基于工作流的业务应用程序,例如流程自动化或类似状态机的系统。

NuGet 链接

在 .NET 中安装包:

代码语言:javascript
代码运行次数:0
复制
dotnet add package Elsa --version 3.2.1  
dotnet add package Elsa.Server  
dotnet add package Elsa.Persistence.EntityFrameworkCore  
dotnet add package Elsa.Activities.Console

示例使用代码:

代码语言:javascript
代码运行次数:0
复制
public class HelloWorldWorkflow : IWorkflow
{
    public void Build(IWorkflowBuilder builder)
    {
        builder
            .StartWith<WriteLine>(activity => activity.WithText("Hello, World!"));
    }
}



//program.cs


var host = Host.CreateDefaultBuilder(args)
    .ConfigureServices(services =>
    {
        // Add Elsa services
        services.AddElsa(options => options
            .AddConsoleActivities() // Register console activities
            .AddWorkflow<HelloWorldWorkflow>() // Register the HelloWorldWorkflow
            .AddEntityFrameworkStores<WorkflowDbContext>()); // Add Entity Framework Core persistence

         services.AddDbContext<WorkflowDbContext>(options =>
             options.UseSqlite("Data Source=workflows.db"));
    })
    .Build();



// Run the workflow
var workflowInvoker = host.Services.GetRequiredService<IWorkflowInvoker>();
await workflowInvoker.StartAsync("HelloWorldWorkflow");

Console.WriteLine("Workflow completed.");

8. NServiceBus

目的: 用于 .NET 的消息传送平台,用于构建分布式和可伸缩系统。

特征:

  • 为消息处理、重试和监控提供企业级支持。
  • 提供与 RabbitMQ、Azure 服务总线和 MSMQ 的无缝集成。
  • 开箱即用的功能,如延迟交付、发布/订阅和 saga,用于管理长时间运行的工作流。

专为需要强大消息处理和分布式系统的大型企业系统而设计。

NuGet 链接

在 .NET 中安装包:

代码语言:javascript
代码运行次数:0
复制
dotnet add package NServiceBus --version 9.2.2

示例使用代码:

代码语言:javascript
代码运行次数:0
复制
using NServiceBus;
using System.Threading.Tasks;

public class MyMessageHandler : IHandleMessages<MyMessage>
{
    public Task Handle(MyMessage message, IMessageHandlerContext context)
    {
        Console.WriteLine($"Received message: {message.Content}");
        return Task.CompletedTask;
    }
}


using NServiceBus;

class Program
{
    static async Task Main(string[] args)
    {
        // Create a new endpoint configuration
        var endpointConfiguration = new EndpointConfiguration("NServiceBusDemo");

        // Use LearningTransport for testing
        endpointConfiguration.UseTransport<LearningTransport>();

        // Enable the message handler
        endpointConfiguration.RegisterComponents(components =>
        {
            components.ConfigureComponent<MyMessageHandler>(DependencyLifecycle.InstancePerUnitOfWork);
        });

        // Start the endpoint
        var endpointInstance = await Endpoint.Start(endpointConfiguration)
            .ConfigureAwait(false);

        // Send a message
        var myMessage = new MyMessage { Content = "Hello, NServiceBus!" };
        await endpointInstance.Send(myMessage)
            .ConfigureAwait(false);

        Console.WriteLine("Message sent. Press Enter to exit.");
        Console.ReadLine();

        // Stop the endpoint
        await endpointInstance.Stop()
            .ConfigureAwait(false);
    }
}

9. Refit

目的: 适用于 .NET 的 REST API 客户端生成器,用于创建类型安全的 HTTP 客户端。

特征:

  • 使用接口自动生成 REST API 客户端。
  • 支持查询参数、标头和内容的属性。
  • 内置对使用 Newtonsoft.Json 或 System.Text.Json 等库进行反序列化的支持。

非常适合希望在使用外部 REST API 时减少样板代码的开发人员。

NuGet 链接

在 .NET 中安装包:

代码语言:javascript
代码运行次数:0
复制
dotnet add package Refit --version 7.2.1

示例使用代码:

代码语言:javascript
代码运行次数:0
复制
// create interface
public interface IGitHubApi
{
    [Get("/users/{user}")]
    Task<User> GetUser(string user);
}

//in service

var gitHubApi = RestService.For<IGitHubApi>("https://api.github.com");
var octocat = await gitHubApi.GetUser("octocat");


// add in program.cs
services
    .AddRefitClient<IGitHubApi>()
    .ConfigureHttpClient(c => c.BaseAddress = new Uri("https://api.github.com"));

10. IdentityServer4

目的: 适用于 ASP.NET Core 的 OpenID Connect 和 OAuth 2.0 框架。

特征:

  • 完全支持保护微服务和 API。
  • 实现基于令牌的身份验证和授权。
  • 支持移动应用程序、SPA 和传统 Web 应用程序等客户端。

用于高度安全、基于令牌的身份验证系统,尤其是微服务或多平台应用程序。

NuGet 链接

在 .NET 中安装包:

代码语言:javascript
代码运行次数:0
复制
dotnet add package IdentityServer4 --version 4.1.2

示例使用代码:

代码语言:javascript
代码运行次数:0
复制
using Microsoft.AspNetCore.Authentication.JwtBearer;

var builder = WebApplication.CreateBuilder(args);

// Add authentication services
builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
    options.Authority = "https://localhost:5001"; // Your IdentityServer URL
    options.RequireHttpsMetadata = false; // Set to true in production
    options.Audience = "api1";
});

builder.Services.AddAuthorization();

var app = builder.Build();

// Use authentication and authorization
app.UseAuthentication();
app.UseAuthorization();

app.MapGet("/api/values", () => new[] { "value1", "value2" })
    .RequireAuthorization();

app.Run();

11. CacheManager.Core

目的: 支持多个缓存提供程序的 .NET 高级缓存抽象层。

特征:

  • 适用于 Redis、Memcached 等。
  • 分层缓存策略(本地和分布式缓存)。
  • 提供高级缓存功能,如过期策略和缓存统计信息。

为分布式系统提供强大的缓存解决方案,从而提高性能和可扩展性。

NuGet 链接

在 .NET 中安装包:

代码语言:javascript
代码运行次数:0
复制
dotnet add package CacheManager.Core --version 1.2.0

示例使用代码:

代码语言:javascript
代码运行次数:0
复制
using CacheManager.Core;
using System;

class Program
{
    static void Main(string[] args)
    {
        // Create a cache manager instance
        var cache = CacheFactory.Build<string>(settings =>
        {
            settings.WithSystemRuntimeCacheHandle("handleName"); // Use the default in-memory cache
        });

        // Add an item to the cache
        cache.Add("key1", "Hello, CacheManager!");

        // Retrieve the item from the cache
        var cachedValue = cache.Get("key1");

        Console.WriteLine(cachedValue); // Output: Hello, CacheManager!

        // Remove the item from the cache
        cache.Remove("key1");

        // Check if the item is still in the cache
        var removedValue = cache.Get("key1");
        Console.WriteLine(removedValue == null ? "Item not found in cache." : removedValue);
    }
}

12. Ocelot

**目的:**适用于 .NET Core 中微服务的轻量级 API 网关。

特征:

  • 路由、聚合和请求转换。
  • 负载均衡、服务发现和速率限制。
  • 身份验证和授权集成。

非常适合构建微服务架构的开发人员,这些架构需要一个网关进行 API 路由、聚合和管理。

NuGet 链接

在 .NET 中安装包:

代码语言:javascript
代码运行次数:0
复制
dotnet add package Ocelot --version 23.3.4

示例使用代码:

代码语言:javascript
代码运行次数:0
复制
{
  "Routes": [
    {
      "DownstreamPathTemplate": "/api/values",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 5001
        }
      ],
      "UpstreamPathTemplate": "/gateway/values",
      "UpstreamHttpMethod": [ "GET" ]
    }
  ],
  "GlobalConfiguration": {
    "BaseUrl": "http://localhost:5000"
  }
}

利用前 10 个专有 NuGet 包可以显著增强您的 .NET 开发体验。这些精心挑选的工具提供了基本功能,可简化流程、提高效率并扩展项目中的功能。通过将这些软件包集成到您的工作流程中,您不仅可以节省时间,还可以提高应用程序的质量。利用这些资源,让您的_开发之旅能够在 .NET 中创建强大、可扩展的解决方案!

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2024-11-18,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 DotNet NB 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. MassTransit
  • 2. Rebus
  • 3. HotChocolate(适用于 .NET 的 GraphQL)
  • 4. Akka.NET
  • 5. Grpc.AspNetCore
  • 6. Steeltoe.Common.Net
  • 7. Elsa
  • 8. NServiceBus
  • 9. Refit
  • 10. IdentityServer4
  • 11. CacheManager.Core
  • 12. Ocelot
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档