.NET Core #dotnet

The .NET Core platform is a new .NET stack that is optimized for open source development and agile delivery on NuGet.

Advantages:

Cross platform framework-Windows, Linux and mac OS for building modern web apps and web APIs

Open Source-Free to use

Integration of Modern UI Framework-Angular, React

Hosting-Kestrel, IIS and nginx

Build in Dependency Injection -Loosely coupled, Reusability

Architected for testability

Razor Pages for easier coding of page-focused scenarios

Unparalleled performance, scalability, and versatility

?

Disadvantages

  1. Development requires a lot of expenses on Visual Studio IDE and other services.
  2. Tooling in the .NET environment is exceedingly complicated and demanding, despite Microsoft's constant improvements.
  3. Limited Object Relational (OR) support.
  4. Managed code that you run with .NET can be slower than native code.
  5. Applications require technologies like workflow, webforms or WCF that are not present in .NET Core.

?

Configure Services Method:

·?????? Configuring services in .NET Core involves setting up dependency injection and configuring various services your application will use.?

·?????? ?The?Program.cs?file is where you configure services and the app pipeline.

·?????? It is optional

·?????? Add services to the container: Use the?builder.Services?property to add services.?

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddTransient<IMyService, MyService>();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();

app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllers();

app.Run();        


configuration settings:

·?????? You can access configuration settings from various sources like?appsettings.json, environment variables, etc.?

var builder = WebApplication.CreateBuilder(args);

// Load configuration from appsettings.json

builder.Configuration.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

var app = builder.Build();        


Configure Methods:

·?????? The?Configure?method is used to define how the application will respond to HTTP requests. This method sets up the middleware components that handle requests and responses.

public class Startup
{
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }
        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();

        });

    }

}        


Key Differences

  • ConfigureServices: Registers services with the DI container.
  • Configure: Sets up the middleware pipeline to handle HTTP requests.

?

Dependency Injection

·?????? Helps to create loosely coupled design of the application.

o?? Register Services

·?????? Addresses several key problems in ASP.NET Core, leading to a more robust and maintainable application:

o?? Tight Coupling.

o?? Code Rigidity.

o?? Testing Difficulties.

o?? Maintainability Challenges.

?

Service Lifetimes:

  • Transient: Created each time they are requested. Use for lightweight, stateless services.(Per User , Per Request)
  • Scoped: Created once per request. Use for services that maintain state within a request.(Per User)
  • Singleton: Created the first time they are requested and then reused for every subsequent request. Use for stateful services.(Request)

Inject Services:

·?????? You can inject services into your controllers or other classes via constructor injection.

public class MyController : ControllerBase
{
    private readonly IMyService _myService;

    public MyController(IMyService myService)
    {
        _myService = myService;
    }

    [HttpGet]
    public IActionResult Get()
    {
        var result = _myService.DoSomething();
        return Ok(result);
    }
}        


Using DI in Middleware:

·?????? You can also inject services into middleware components.

public class MyMiddleware
{
    private readonly RequestDelegate _next;
    private readonly IMyService _myService;

    public MyMiddleware(RequestDelegate next, IMyService myService)
    {
        _next = next;
        _myService = myService;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        _myService.DoSomething();
        await _next(context);
    }
}        


Configuration and Options Pattern:

·?????? You can use the options pattern to manage configuration settings.

public class MyOptions
{
    public string Option1 { get; set; }
    public int Option2 { get; set; }
}


// Register options

builder.Services.Configure<MyOptions>(builder.Configuration.GetSection("MyOptions"));

// Inject options

public class MyService
{
    private readonly MyOptions _options;

    public MyService(IOptions<MyOptions> options)
    {
        _options = options.Value;

    }
}

         

Kestrel:

·?????? Kestrel is?a cross-platform web server for ASP.NET Core. Kestrel is the recommended server for ASP.NET Core, and it's configured by default in ASP.NET Core project templates.

?

Key Features of Kestrel

  1. Cross-Platform: Runs on Windows, Linux, and macOS.
  2. High Performance: Optimized to handle a large number of concurrent connections efficiently.
  3. Lightweight: Suitable for resource-constrained environments, such as containers and edge devices.
  4. Security: Supports HTTPS and is hardened against web server vulnerabilities.
  5. Protocol Support: Supports HTTP/1.1, HTTP/2, HTTP/3, and WebSockets.
  6. Integration: Seamlessly integrates with ASP.NET Core components like middleware, dependency injection, and configuration systems

Configuring Kestrel

·?????? You can configure Kestrel in the?Program.cs?file or in the?appsettings.json?file.

var builder = WebApplication.CreateBuilder(args);

// Configure Kestrel server options

builder.WebHost.ConfigureKestrel(serverOptions =>
{
    serverOptions.Limits.MaxConcurrentConnections = 100;
    serverOptions.Limits.MaxRequestBodySize = 10 * 1024;
    serverOptions.Listen(IPAddress.Any, 5000); // Listen on port 5000
});

var app = builder.Build();

app.MapGet("/", () => "Hello World!");

app.Run();        


Use Kestrel

var builder = WebApplication.CreateBuilder(args);

var app = builder.Build();

app.MapGet("/", () => "Hello World!");

app.Run();        

Architecture:

·?????? The architecture of .NET Core is designed to be modular, lightweight, and cross-platform, making it suitable for building modern, high-performance applications

·?????? Built on .NET Core runtime

Key Components

  1. CoreCLR: The runtime that executes .NET Core applications. It includes the Just-In-Time (JIT) compiler, garbage collector, and other runtime services.
  2. CoreFX: The foundational class libraries that provide a wide range of functionalities, such as collections, file I/O, and networking.
  3. ASP.NET Core: A framework for building web applications and services. It includes features like MVC, Razor Pages, Web API, and SignalR.
  4. Entity Framework Core: An object-relational mapper (ORM) for .NET Core, which simplifies data access by allowing developers to work with a database using .NET objects.
  5. CLI (Command-Line Interface): Tools for building, running, and managing .NET Core applications from the command line.
  6. NuGet: The package manager for .NET, which allows developers to share and consume reusable code.

Architectural Concepts

  1. Modularity: .NET Core is composed of NuGet packages, allowing developers to include only the libraries they need, reducing the application’s footprint.
  2. Cross-Platform: .NET Core runs on Windows, macOS, and Linux, enabling developers to build and deploy applications on multiple platforms.
  3. High Performance: Optimized for performance and scalability, making it suitable for cloud-based and high-traffic applications.
  4. Microservices: Supports building microservices architectures, where applications are composed of small, independent services that communicate over HTTP or other protocols.
  5. Dependency Injection: Built-in support for dependency injection, which promotes loose coupling and testability.
  6. Middleware: ASP.NET Core uses a middleware pipeline to handle HTTP requests and responses, allowing developers to add custom processing logic.

?

Reading appsetting values

  • Once the configuration is built, you can access values from appsettings.json using the IConfiguration interface injected in your classes or accessed through the Host.Configuration property.
  • You can retrieve values by their key using methods like GetValue<T>("key"), where T is the expected type of the value.

public class MyController : Controller
{
 private readonly IConfiguration _configuration;

public MyController(IConfiguration configuration)
 {
   _configuration = configuration;
 }

 public IActionResult Index()
{
   string connectionString = _configuration.GetValue<string>("ConnectionStrings:Default");

    // Use the connection string to access your database...

  return View();
 }

}        

Middleware

?Middleware in ASP.NET Core is a crucial concept that involves a series of components used to handle requests and responses in an application. Each middleware component in the pipeline can perform operations before and after the next component in the pipeline. Here are some key points about middleware in ASP.NET Core:

1. Request Pipeline: Middleware components are assembled into an app pipeline to handle requests and responses. Each component decides whether to pass the request to the next component or to handle it directly1.

2. Built-in Middleware: ASP.NET Core provides a rich set of built-in middleware components, such as authentication, authorization, logging, and more1.

3. Custom Middleware: You can also create custom middleware to handle specific tasks. Custom middleware is typically encapsulated in a class and exposed with an extension method2.

4. Order of Middleware: The order in which middleware components are added to the pipeline is crucial, as it determines the sequence of request processing1.

5. Short-circuiting: Middleware can short-circuit the pipeline, meaning it can prevent further middleware from processing the request if certain conditions are met.

using System.Globalization;

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.UseHttpsRedirection();
app.Use(async (context, next) => {
    var cultureQuery = context.Request.Query["culture"];
    if (!string.IsNullOrWhiteSpace(cultureQuery)) {
        var culture = new CultureInfo(cultureQuery);
        CultureInfo.CurrentCulture = culture;
        CultureInfo.CurrentUICulture = culture;
    }
    await next(context);
});

app.Run(async (context) => {
    await context.Response.WriteAsync($"CurrentCulture.DisplayName: {CultureInfo.CurrentCulture.DisplayName}");
});

app.Run();
        

?App.Run:

In .NET Core, the app.Run method is used to define a terminal middleware delegate in the application’s request pipeline. This means it handles the request and generates a response directly, without passing the request to any subsequent middleware components.

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.Run(async context =>
{
    await context.Response.WriteAsync("Hello, World!");
});

app.Run();        

In this example, the app.Run method is used to respond with “Hello, World!” to any incoming HTTP request. Once app.Run is called, it terminates the pipeline, meaning no further middleware will be executed

App.Use:

In .NET Core, the app.Use method is used to add middleware components to the application’s request pipeline. Middleware are software components that are assembled into an application pipeline to handle requests and responses. Each component chooses whether to pass the request to the next component in the pipeline.

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.Use(async (context, next) =>
{
    // Do something before the next middleware
    await context.Response.WriteAsync("Before next middleware\n");
    
    await next.Invoke(); // Call the next middleware

    // Do something after the next middleware
    await context.Response.WriteAsync("After next middleware\n");
});

app.Run(async context =>
{
    await context.Response.WriteAsync("Hello from the terminal middleware!\n");
});

app.Run();
        

  • The app.Use method adds a middleware that writes a message before and after calling the next middleware in the pipeline.
  • The next.Invoke() method is used to call the next middleware component.
  • The app.Run method is used to define a terminal middleware that writes a final message and ends the request pipeline


要查看或添加评论,请登录

Tarakeswhara Rao Bandla的更多文章

  • C#

    C#

    C# is a versatile and powerful programming language developed by Microsoft as part of the .NET platform.

  • Message Queuing Microservices

    Message Queuing Microservices

    1. Message Queuing A message queue is a middleware technology that acts as a buffer for messages between applications…

  • OOPs with C#

    OOPs with C#

    Object Oriented Programming(OO)P is a programming paradigm that revolves around creating objects that model real-world…

    2 条评论
  • Design Patterns for Dot Net #dotnet #designpatterns

    Design Patterns for Dot Net #dotnet #designpatterns

    Design Patterns Reusable solutions to common software design problems that promote good object-oriented principles…

  • Solid Principles with Real-Time

    Solid Principles with Real-Time

    The SOLID principles! These are five fundamental design principles in object-oriented programming that promote creating…

  • Beyond Tomorrow

    Beyond Tomorrow

    Stages of Artificial Intelligence Artificial Intelligence(AI) is the intelligence exhibited by machines or software, as…

    1 条评论

社区洞察

其他会员也浏览了