I have a regular ASP.NET app, which uses routes and etc. I also want to add WebSockets with database connections to the app, and have come to the conclusion middleware is the best way to do this, but I can not get it to work with the database. This is currently my WebSocketMiddleware class:
public class WebSocketMiddleware
{
private readonly RequestDelegate next;
private readonly DatabaseService databaseService;
public WebSocketMiddleware(RequestDelegate next, DatabaseService databaseService)
{
this.next = next;
this.databaseService = databaseService;
}
public async Task Invoke(HttpContext context)
{
if (context.WebSockets.IsWebSocketRequest)
{
WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync();
await HandleWebSocketConnection(context, webSocket);
} else
{
Console.WriteLine("Not ws");
await next(context);
}
}
and this is the Program:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddDbContext<DatabaseContext>(options =>
options.UseNpgsql("address"));
builder.Services.AddScoped<DatabaseService>();
builder.Services.AddScoped<WebSocketMiddleware>();
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowLocalhost",
builder =>
{
builder.WithOrigins("https://localhost:3000")
.AllowAnyHeader()
.AllowCredentials()
.AllowAnyMethod();
});
});
var app = builder.Build();
app.UseCors("AllowLocalhost");
app.UseWebSockets();
app.UseMiddleware<WebSocketMiddleware>();
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
And this is the DatabaseService I am attempting to inject:
public class DatabaseService
{
private readonly DatabaseContext databaseContext;
public DatabaseService(DatabaseContext databaseContext)
{
this.databaseContext = databaseContext;
}
// methods //
}
I have tried removing and adding WebSocketMiddleware as AddScoped, but both fails from their own reasons. If I remove the DatabaseService from the middleware, it works as expected.
Errors: When adding scoped: 'Unable to resolve service for type Http.RequestDelegate while attempting to activate WebSocketMiddleware'
When removing scoped: 'Cannot resolve scoped service DatabaseService from root provider'
If I remove RequestDelegate from the middleware, I get this error: 'A suitable constructor for type WebSocketMiddleware could not be located'