私は、.netコアをテストしていて、.netコア+ウェブソケットを使用して小さなサンプルアプリケーションを作成して、アプリケーションにデータをプッシュします。 dbcontextを使用してこのデータをデータベースに保存します。.net core websocketsはDbContextを取得します
しかし、websocketハンドラでdbcontextを取得する際に問題があります。では、どのように使用するdbcontextを作成できますか?
私のスタートアップの設定方法は、これを含んでいます
...
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
}
}
}
こんにちは、@ジョンスミス。あなたはこの問題を解決しましたか?私は今解決策を探しています – Mergasov
@Mergasovはいコードに行くことを許可し、私は答えを投稿します。 –