gpt4 book ai didi

c# - .Net 核心启动基类

转载 作者:太空狗 更新时间:2023-10-29 20:06:58 24 4
gpt4 key购买 nike

希望使用 .Net 核心创建一套微服务,我正在考虑为 Startup 类创建一个基类,它将负责配置常见功能,如日志记录、身份验证、端点健康检查,从而标准化我们所有的服务。

然而令我惊讶的是,这种模式似乎并没有被提及。是使用自定义中间件来实现通用功能的首选模式吗?任何与此困境相关的想法或经验都将不胜感激。

最佳答案

Microsoft.Extensions.DependencyInjection 命名空间中为 IServiceCollection 和/或 IApplicationBuilder 接口(interface)创建扩展方法:

public static IServiceCollection AddAllCoolStuff(this IServiceCollection services)
{
if (services == null)
{
throw new ArgumentNullException(nameof(services));
}

services.AddSingleton<FooService>();
services.AddTransient<IBooService, BooService>();
...

return services;
}

public static IApplicationBuilder UseAllCoolStuff(this IApplicationBuilder app)
{
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}

app.UseMiddleware<SomeCoolMiddleware>();
...

return app;
}

并在您的 Startup 中使用它们:

public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddAllCoolStuff();
}

public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
app.UseAllCoolStuff();
}
}

关于c# - .Net 核心启动基类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44755011/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com