Wishing to use .Net core to create a suite of micro services, I was thinking of creating a base class for the Startup class which would be responsible for configuring common features such as logging, authentication, endpoint health checks therefore standardizing all our services.
I was surprised however that such a pattern does not seem to be mentioned. Is the preferred pattern to use custom middleware for common functionality instead? Any thoughts or experience in relation to this dilemma would be appreciated.
The Startup classA service is a reusable component that provides app functionality. Services are registered in ConfigureServices and consumed across the app via dependency injection (DI) or ApplicationServices. Includes a Configure method to create the app's request processing pipeline.
As a C# programming language known for strong typing, . NET Core gets another point for being excellent for startups. Languages like that allow implementing architecture and project patterns for modular and scalable development which results in high code quality.
The following is a default Startup class in ASP.NET Core 2. x. startup.cs. As you can see, Startup class includes two public methods: ConfigureServices and Configure. The Startup class must include a Configure method and can optionally include ConfigureService method.
Now To add Startup. cs to ASP.NET Core 6.0 project, add a new class named Startup. cs and add the below code. So in the above code, you can see, that we have added a startup class and added 2 methods ConfigureServices and Configure as we used to have in the previous version of asp.net.
Create extensions methods for IServiceCollection
and/or IApplicationBuilder
interfaces in Microsoft.Extensions.DependencyInjection
namespace:
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;
}
And use them in your Startup's:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddAllCoolStuff();
}
public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
app.UseAllCoolStuff();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With