.Net核心启动基类

Mr *_*ies 8 c# .net-core asp.net-core

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

然而,我很惊讶这样的模式似乎没有被提及.是使用自定义中间件来实现常用功能的首选模式吗?任何有关这种困境的想法或经验都将受到赞赏.

Dmi*_*try 9

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

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;
}
Run Code Online (Sandbox Code Playgroud)

并在你的Startup中使用它们:

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

    public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
    {
        app.UseAllCoolStuff();
    }
}
Run Code Online (Sandbox Code Playgroud)