Difference between Middleware and Services in ASP.NET Core
Middleware और Services
ASP.NET Core में Middleware और Services दोनों अलग-अलग कॉन्सेप्ट हैं, लेकिन वे आपस में जुड़े हुए हो सकते हैं। आइए समझते हैं कि Middleware और Services में क्या अंतर हैं।
1. Middleware और Services में अंतर
Feature | Middleware | Services |
---|---|---|
परिभाषा | HTTP रिक्वेस्ट और रिस्पॉन्स पाइपलाइन का हिस्सा जो अनुरोधों को प्रोसेस करता है। | Dependency Injection (DI) के माध्यम से एप्लिकेशन में उपयोग की जाने वाली क्लासेज। |
Execution Flow | अनुरोध और प्रतिक्रिया के बीच स्थित होते हैं। | अनुरोध पूरा करने में मदद करने के लिए बैकग्राउंड में काम करते हैं। |
उदाहरण | UseRouting() , UseAuthentication() , UseSession() |
DbContext , ILogger , IConfiguration |
कैसे रजिस्टर करें? | app.UseMiddleware<CustomMiddleware>() |
services.AddScoped<IMyService, MyService>() |
2. Middleware क्या है
Middleware एक ऐसा कंपोनेंट होता है जो HTTP रिक्वेस्ट और रिस्पॉन्स को इंटरसेप्ट करता है और उनमें कुछ प्रोसेसिंग करता है। ASP.NET Core में Middleware को Pipeline के रूप में व्यवस्थित किया जाता है।
Middleware रजिस्टर करने का तरीका (Program.cs)
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.UseRouting(); // Middleware for Routing
app.UseAuthentication(); // Middleware for Authentication
app.UseAuthorization(); // Middleware for Authorization
app.UseSession(); // Middleware for Session
app.Run(async (context) => {
await context.Response.WriteAsync("Hello, World!");
});
3. Services क्या हैं
Services वे क्लासेज होती हैं जिन्हें Dependency Injection (DI) के माध्यम से उपयोग किया जाता है। Services को Program.cs
में builder.Services.AddSingleton
, AddScoped
, या AddTransient
द्वारा रजिस्टर किया जाता है।
Service रजिस्टर करने का तरीका
builder.Services.AddSingleton<IMyService, MyService>();
Service का उपयोग किसी Controller में
public class HomeController : Controller
{
private readonly IMyService _myService;
public HomeController(IMyService myService)
{
_myService = myService;
}
public IActionResult Index()
{
var data = _myService.GetData();
return View(data);
}
}
4. Middleware और Services का संबंध
Middleware में Services को Dependency Injection के माध्यम से उपयोग किया जा सकता है। Custom Middleware जो Service को उपयोग करता है:
public class MyMiddleware
{
private readonly RequestDelegate _next;
private readonly IMyService _myService;
public MyMiddleware(RequestDelegate next, IMyService myService)
{
_next = next;
_myService = myService;
}
public async Task Invoke(HttpContext context)
{
var data = _myService.GetData();
await context.Response.WriteAsync($"Data: {data}");
await _next(context);
}
}
Custom Middleware को पाइपलाइन में जोड़ना
app.UseMiddleware<MyMiddleware>();
Next: ASP.NET कोर में मिडलवेयर और सर्विस क्लास के बीच व्यवहार में अंतर
टिप्पणियाँ
एक टिप्पणी भेजें