I am testing the .net core and building a small sample application using .net core + websockets to insert some data into my application. I want to store this data in a database using dbcontext.
However, I am having problems getting dbcontext in my websocket handler. So how can I create a dbcontext to use.
My Configure startup method contains the following:
...
app.Map("/ws", WSHandler.Map);
...
This is my WSHandler class, which actually does a read from an incoming connection. I need a DbContext here, which I can use to read / write from the database.
public class WSHandler {
public const int BufferSize = 4096;
WebSocket socket;
WSHandler(WebSocket socket) {
this.socket = socket;
}
public static void Map(IApplicationBuilder app) {
app.UseWebSockets();
app.Use((WSHandler.Acceptor);
}
static async Task Acceptor(HttpContext hc, Func<Task> n) {
if (hc.WebSockets.IsWebSocketRequest == false) {
return;
}
var socket = await hc.WebSockets.AcceptWebSocketAsync();
var h = new WSHandler(socket);
await h.Loop();
}
async Task Loop() {
var buffer = new Byte[BufferSize];
ArraySegment<Byte> segment = new ArraySegment<byte>(buffer);
while (this.socket.State == WebSocketState.Open) {
WebSocketReceiveResult result = null;
do {
result = await socket.ReceiveAsync(segment, CancellationToken.None);
} while (result.EndOfMessage == false);
}
}
}
source
share