我正在测试 .net core,并使用 .net core + websockets 创建一个小的示例应用程序,以将一些数据推送到我的应用程序中。我希望使用 dbcontext 将这些数据保存在数据库中。
然而,我在 websocket 处理程序中遇到了获取 dbcontext 的问题。那么我该如何创建一个可用的 dbcontext 呢?
我的启动 Configure 方法包含以下内容:
...
app.Map("/ws", WSHandler.Map);
...
这是我的WSHandler类,实现从传入连接中读取数据。我需要一个DbContext,以便可以用它来读写数据库。
/// <summary>
/// Handler for an incoming websocket client
/// </summary>
public class WSHandler {
/// <summary>
/// Max size in bytes of an incoming/outgoing message
/// </summary>
public const int BufferSize = 4096;
/// <summary>
/// The socket of the current connection
/// </summary>
WebSocket socket;
/// <summary>
/// Constructor, assign socket to current instance and adds socket to ConnectedClients.
/// </summary>
/// <param name="socket"></param>
WSHandler(WebSocket socket) {
this.socket = socket;
}
/// <summary>
/// Configure app to use websockets and register handler.
/// </summary>
/// <param name="app"></param>
public static void Map(IApplicationBuilder app) {
app.UseWebSockets();
app.Use((WSHandler.Acceptor);
}
/// <summary>
/// Accept HttpContext and handles constructs instance of WSHandler.
/// </summary>
/// <param name="hc">The HttpContext</param>
/// <param name="n">Task n</param>
/// <returns></returns>
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();
}
/// <summary>
/// Wait's for incoming messages
/// </summary>
/// <returns></returns>
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);
// do something with message here. I want to save parse and save to database
}
}
}