.NET Core中值得推荐使用的10大优秀库,你用到过几个?

f573effa5396cd2bc7a6bfc2e87de655.jpeg

概述:Microsoft 的 .NET Core 生态系统中的中间件已经发生了重大变化,包括无缝集成到应用程序管道中的内置和第三方组件,协调客户端和服务器之间的数据流。它通过身份验证、日志记录和路由等功能增强了应用程序功能,确保了可扩展性和可维护性我将展示 Microsoft 的十种出色的中间件解决方案。无论你是经验丰富的开发人员还是 .NET Core 新手,此探索都提供了宝贵的见解和资源来增强你的开发项目。AutoMapper它是软件开发中的一个库,可简化不同对象类型之间的数据传输。开发人员无需手动复制每个属性,而是通过简单的配置过程定义映射。这种自动化可以节省时间,减少错误,并增强代码的可读性

Microsoft 的 .NET Core 生态系统中的中间件已经发生了重大变化,包括无缝集成到应用程序管道中的内置和第三方组件,协调客户端和服务器之间的数据流。它通过身份验证、日志记录和路由等功能增强了应用程序功能,确保了可扩展性和可维护性

我将展示 Microsoft 的十种出色的中间件解决方案。无论你是经验丰富的开发人员还是 .NET Core 新手,此探索都提供了宝贵的见解和资源来增强你的开发项目。

  1. AutoMapper

它是软件开发中的一个库,可简化不同对象类型之间的数据传输。开发人员无需手动复制每个属性,而是通过简单的配置过程定义映射。这种自动化可以节省时间,减少错误,并增强代码的可读性和可维护性。通过消除手动任务,AutoMapper 使开发人员能够专注于应用程序逻辑,使其成为各种规模项目的宝贵工具。最终,它简化了对象映射,促进了高效且易于管理的软件开发。

通常在应用程序初始化阶段设置映射。

public class SourceClass  
{  
    public int Id { get; set; }  
    public string Name { get; set; }  
    // Other properties  
}  
  
public class DestinationClass  
{  
    public int Id { get; set; }  
    public string Name { get; set; }  
    // Other properties  
}

将 AutoMapper 配置为将属性从SourceClassDestinationClass.

using AutoMapper;  
  
public class MappingProfile : Profile  
{  
    public MappingProfile()  
    {  
        CreateMap<SourceClass, DestinationClass>();  
        // You can define more mappings here if needed  
    }  
}  
  
  
public class Startup  
{  
    public void ConfigureServices(IServiceCollection services)  
    {  
        // Other service configurations  
  
        services.AddAutoMapper(typeof(MappingProfile)); // Register MappingProfile  
    }  
}  
  
public class YourService  
{  
    private readonly IMapper _mapper;  
  
    public YourService(IMapper mapper)  
    {  
        _mapper = mapper;  
    }  
  
    public DestinationClass MapObjects(SourceClass source)  
    {  
        // Mapping SourceClass object to DestinationClass object  
        DestinationClass destination = _mapper.Map<SourceClass, DestinationClass>(source);  
        return destination;  
    }  
}

2. Swagger

它通过基于 API 端点、模型和元数据自动生成详细文档来简化 Swagger 文档的创建。其主要功能包括:

  • 生成 API 端点、HTTP 方法和请求/响应模型的文档。

  • 它提供了一个交互式的 Swagger UI,使用户能够直接探索和测试 API 功能。

  • 与 ASP.NET Core 应用程序无缝集成,只需最少的配置。

  • 提供用于控制 Swagger UI 的外观和行为的自定义选项。

  • 允许用户通过在 Swagger UI 中执行请求和检查响应来测试 API 功能。

using Microsoft.Extensions.DependencyInjection;  
using Microsoft.OpenApi.Models;  
  
public class Startup  
{  
    public void ConfigureServices(IServiceCollection services)  
    {  
        services.AddControllers();  
  
        // Register the Swagger generator  
        services.AddSwaggerGen(c =>  
        {  
            c.SwaggerDoc("v1", new OpenApiInfo { Title = "Your API", Version = "v1" });  
        });  
    }  
  
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)  
    {  
        if (env.IsDevelopment())  
        {  
            app.UseDeveloperExceptionPage();  
  
            // Enable middleware to serve generated Swagger as a JSON endpoint  
            app.UseSwagger();  
  
            // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint  
            app.UseSwaggerUI(c =>  
            {  
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "Your API V1");  
            });  
        }  
  
        app.UseRouting();  
        app.UseAuthorization();  
  
        app.UseEndpoints(endpoints =>  
        {  
            endpoints.MapControllers();  
        });  
    }  
}

3. Hangfire

它是一个功能强大的库,用于在 .NET 和 .NET Core 应用程序中执行后台任务。其主要功能包括:

  • 允许异步任务执行,而不会阻塞主应用程序线程。

  • 使计划任务能够按设定的时间间隔或延迟后运行,从而自动执行重复性进程。

  • 提供用户友好的界面来监视和管理后台任务。

  • 通过持久存储作业信息来确保任务执行的一致性。

using Hangfire;  
using System;  
  
public class MyBackgroundJobService  
{  
    public void ExecuteBackgroundTask()  
    {  
        // Example of executing a background task using Hangfire  
        BackgroundJob.Enqueue(() => SomeBackgroundTaskMethod());  
    }  
  
    public void ScheduleDelayedTask()  
    {  
        // Example of scheduling a delayed task using Hangfire  
        BackgroundJob.Schedule(() => SomeDelayedTaskMethod(), TimeSpan.FromMinutes(30));  
    }  
  
    public void ScheduleRecurringTask()  
    {  
        // Example of scheduling a recurring task using Hangfire  
        RecurringJob.AddOrUpdate(() => SomeRecurringTaskMethod(), Cron.Daily);  
    }  
  
    public void SomeBackgroundTaskMethod()  
    {  
        // Logic for executing a background task  
        Console.WriteLine("Executing background task...");  
    }  
  
    public void SomeDelayedTaskMethod()  
    {  
        // Logic for executing a delayed task  
        Console.WriteLine("Executing delayed task...");  
    }  
  
    public void SomeRecurringTaskMethod()  
    {  
        // Logic for executing a recurring task  
        Console.WriteLine("Executing recurring task...");  
    }  
}

4. Serilog

  • 允许将事件记录到各种输出,如文件、数据库和控制台。

  • 支持结构化日志记录,使开发人员能够使用丰富的结构化数据记录事件,以提高可读性和分析能力。

  • 提供查询功能,实现高效的日志分析,使开发人员能够从记录的事件中提取有意义的见解。

using Serilog;  
using Serilog.Events;  
using Serilog.Formatting.Json;  
using System;  
  
public class Program  
{  
    public static void Main(string[] args)  
    {  
        // Configure Serilog to log to a file, console, and database  
        Log.Logger = new LoggerConfiguration()  
            .MinimumLevel.Debug()  
            .WriteTo.Console()  
            .WriteTo.File("log.txt")  
            .WriteTo.MSSqlServer(connectionString: "YourConnectionString",  
                                  tableName: "Logs",  
                                  columnOptions: new Serilog.Sinks.MSSqlServer.ColumnOptions(),  
                                  restrictedToMinimumLevel: LogEventLevel.Information)  
            .CreateLogger();  
  
        // Log an event with structured data  
        Log.Information("This is a structured event with {Property1} and {Property2}", "value1", "value2");  
  
        // Querying logs  
        var logs = Log.ReadFrom.MSSqlServer("YourConnectionString", "Logs")  
                     .Query()  
                     .Where(l => l.Level == LogEventLevel.Information && l.MessageTemplate.Text.Contains("structured"))  
                     .OrderByDescending(l => l.Timestamp)  
                     .ToList();  
          
        foreach (var log in logs)  
        {  
            Console.WriteLine($"Timestamp: {log.Timestamp}, Level: {log.Level}, Message: {log.MessageTemplate.Text}");  
        }  
  
        // Dispose the logger  
        Log.CloseAndFlush();  
    }  
}

5. NancyFx

  • 路由 — 提供路由以进行高效的HTTP请求处理。

  • 依赖注入 — 支持轻松集成外部组件。

  • 模型绑定 — 有助于将 HTTP 请求数据映射到 .NET 对象。

  • 可扩展性 — 高度可定制以满足特定要求。

  • 轻量级 — 以最小的开销针对性能进行了优化。

using Nancy;  
  
public class SampleModule : NancyModule  
{  
    public SampleModule()  
    {  
        // Routing example  
        Get("/", _ => "Hello, World!"); // Responds to GET requests at the root URL with "Hello, World!"  
  
        // Dependency Injection example  
        var myService = new MyService(); // Instantiate your service  
        Get("/dependency-injection-example", _ => myService.GetData()); // Inject and use your service  
  
        // Model Binding example  
        Post("/model-binding-example", args =>  
        {  
            var requestModel = this.Bind\<MyRequestModel>(); // Bind HTTP request data to MyRequestModel object  
            return Negotiate.WithModel(requestModel).WithStatusCode(HttpStatusCode.OK); // Respond with bound object  
        });  
  
        // Extensibility: Implement custom route with specific requirements  
        Get("/custom-route", _ => "Custom route response");  
  
        // Lightweight: No extra setup or configuration needed for basic functionality  
    }  
}  
  
public class MyService  
{  
    public string GetData()  
    {  
        return "Data from MyService";  
    }  
}  
  
public class MyRequestModel  
{  
    public string Property1 { get; set; }  
    public int Property2 { get; set; }  
}

6. MediatR

它有助于采用命令查询责任分离 (CQRS) 模式,该模式将命令执行(状态更改)与查询处理(数据检索)分开,以提高灵活性和可伸缩性。在 ASP.NET Core 中,MediatR 通过提供用于请求处理的抽象来简化 CQRS 实现。开发人员为命令和查询定义处理程序,使他们能够专注于业务逻辑,而不是复杂的基础结构。

// Define a command to represent a state change
public class CreateProductCommand : IRequest<int>
{
    public string Name { get; set; }
    public decimal Price { get; set; }
}

// Define a handler for the command
public class CreateProductCommandHandler : IRequestHandler<CreateProductCommand, int>
{
    private readonly IDbContext _dbContext;

    public CreateProductCommandHandler(IDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    public async Task<int> Handle(CreateProductCommand request, CancellationToken cancellationToken)
    {
        var product = new Product
        {
            Name = request.Name,
            Price = request.Price
        };

        _dbContext.Products.Add(product);
        await _dbContext.SaveChangesAsync();

        return product.Id;
    }
}

// Define a query to represent data retrieval
public class GetProductByIdQuery : IRequest<ProductDto>
{
    public int ProductId { get; set; }
}

// Define a handler for the query
public class GetProductByIdQueryHandler : IRequestHandler<GetProductByIdQuery, ProductDto>
{
    private readonly IDbContext _dbContext;

    public GetProductByIdQueryHandler(IDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    public async Task<ProductDto> Handle(GetProductByIdQuery request, CancellationToken cancellationToken)
    {
        var product = await _dbContext.Products.FindAsync(request.ProductId);

        return product != null ? new ProductDto { Id = product.Id, Name = product.Name, Price = product.Price } : null;
    }
}

// Usage example in controller
public class ProductsController : ControllerBase
{
    private readonly IMediator _mediator;

    public ProductsController(IMediator mediator)
    {
        _mediator = mediator;
    }

    [HttpPost]
    public async Task<ActionResult<int>> CreateProduct(CreateProductCommand command)
    {
        var productId = await _mediator.Send(command);
        return Ok(productId);
    }

    [HttpGet("{id}")]
    public async Task<ActionResult<ProductDto>> GetProduct(int id)
    {
        var query = new GetProductByIdQuery { ProductId = id };
        var product = await _mediator.Send(query);

        if (product == null)
            return NotFound();

        return Ok(product);
    }
}

7. FluentValidation

它是一个用于验证模型的 .NET 库,允许开发人员清楚地定义验证规则。它与 ASP.NET Core MVC 无缝集成,支持在 HTTP 请求中自动验证模型。使用 FluentValidation,开发人员可以简化验证,提高代码可读性,并跨应用程序维护干净的验证逻辑。

// Define a model to be validated
public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

// Create a validator for the model using FluentValidation
public class PersonValidator : AbstractValidator<Person>
{
    public PersonValidator()
    {
        RuleFor(x => x.Name).NotEmpty().WithMessage("Name is required.");
        RuleFor(x => x.Age).InclusiveBetween(18, 100).WithMessage("Age must be between 18 and 100.");
    }
}

// In ASP.NET Core MVC controller, use the validator to automatically validate models in HTTP requests
public class PersonController : ControllerBase
{
    private readonly IValidator<Person> _validator;

    public PersonController(IValidator<Person> validator)
    {
        _validator = validator;
    }

    [HttpPost]
    public IActionResult AddPerson([FromBody] Person person)
    {
        var validationResult = _validator.Validate(person);
        if (!validationResult.IsValid)
        {
            return BadRequest(validationResult.Errors);
        }

        // If the model is valid, continue with the business logic
        // ...
        return Ok("Person added successfully.");
    }
}

8. IdentityServer

它是 ASP.NET Core 中用于身份验证和授权的库。它支持 OAuth2 和 OpenID Connect,集中用户身份管理、身份验证和访问控制。这通过为安全身份验证和授权提供统一的平台来简化开发。借助 IdentityServer,开发人员可以高效地处理身份验证、管理授权策略并保护对资源的访问,从而增强 ASP.NET Core 应用程序的安全性。

// Install IdentityServer4 package via NuGet
// Install-Package IdentityServer4

using IdentityServer4;
using IdentityServer4.Models;
using System.Collections.Generic;

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        // Configure IdentityServer
        services.AddIdentityServer()
            .AddInMemoryClients(new List<Client>
            {
                new Client
                {
                    ClientId = "client",
                    AllowedGrantTypes = GrantTypes.ClientCredentials,
                    ClientSecrets =
                    {
                        new Secret("secret".Sha256())
                    },
                    AllowedScopes = { "api1" }
                }
            })
            .AddInMemoryApiScopes(new List<ApiScope>
            {
                new ApiScope("api1", "My API")
            })
            .AddInMemoryApiResources(new List<ApiResource>())
            .AddDeveloperSigningCredential(); // Use in-memory signing key for development
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseIdentityServer();
    }
}

9. Polly

它是一个 .NET 库,用于增强服务复原能力和容错能力。它提供重试和断路器等策略来有效处理故障。开发人员使用 Polly 来解决网络问题、服务不可用或意外错误。例如,重试策略重试失败的操作,帮助服务从暂时性故障中恢复。断路器策略可防止重复失败的尝试,从而允许服务在设定的时间后恢复运行。通过利用 Polly,开发人员可以创建能够承受故障场景、增强系统稳定性和性能的强大应用程序。

// Import the necessary Polly namespaces
using Polly;
using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        // Define a policy for retrying failed operations
        var retryPolicy = Policy.Handle<HttpRequestException>()
                                 .WaitAndRetryAsync(3, _ => TimeSpan.FromSeconds(1));

        // Define a policy for circuit breaking
        var circuitBreakerPolicy = Policy.Handle<HttpRequestException>()
                                          .CircuitBreakerAsync(2, TimeSpan.FromSeconds(30));

        // Example usage of retry policy
        await retryPolicy.ExecuteAsync(async () =>
        {
            var httpClient = new HttpClient();
            var response = await httpClient.GetAsync("https://api.example.com");
            response.EnsureSuccessStatusCode();
            Console.WriteLine("Request successful!");
        });

        // Example usage of circuit breaker policy
        await circuitBreakerPolicy.ExecuteAsync(async () =>
        {
            var httpClient = new HttpClient();
            var response = await httpClient.GetAsync("https://api.example.com");
            response.EnsureSuccessStatusCode();
            Console.WriteLine("Request successful!");
        });
    }
}

10. XUnit

它是一个主要用于 .NET 生态系统的单元测试库。它使开发人员能够编写和执行单元测试,以验证各个代码单元的功能。遵循测试驱动的开发原则,XUnit 强调简单性、灵活性和可扩展性。它提供测试发现、执行、设置/拆解方法、参数化测试、测试类别和输出捕获等功能。XUnit 通过鼓励使用属性来标记测试方法和将测试问题分离到单独的类中等约定来促进干净和可读的测试代码。

// Example of a simple xUnit test class
using Xunit;

public class MathOperationsTests
{
    // Example of a test method
    [Fact]
    public void Add_TwoNumbers_ReturnsSum()
    {
        // Arrange
        int a = 5;
        int b = 10;

        // Act
        int result = MathOperations.Add(a, b);

        // Assert
        Assert.Equal(15, result);
    }

    // Example of a parameterized test method
    [Theory]
    [InlineData(3, 5, 8)]
    [InlineData(0, 0, 0)]
    [InlineData(-1, 1, 0)]
    public void Add_TwoNumbers_ReturnsCorrectSum(int a, int b, int expected)
    {
        // Act
        int result = MathOperations.Add(a, b);

        // Assert
        Assert.Equal(expected, result);
    }
}

// Example of a class with methods to be tested
public class MathOperations
{
    public static int Add(int a, int b)
    {
        return a + b;
    }
}

如果你喜欢我的文章,请给我一个赞!谢谢

-

技术群:添加小编微信并备注进群

小编微信:mm1552923   

公众号:dotNet编程大全    

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值