2016-12-08 3 views
3

私は、.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 
     } 

    } 
} 
+0

こんにちは、@ジョンスミス。あなたはこの問題を解決しましたか?私は今解決策を探しています – Mergasov

+0

@Mergasovはいコードに行くことを許可し、私は答えを投稿します。 –

答えて

2

この投稿に興味があるので、私が使用したソリューションを追加しました。

HttpContextですべてのサービスにアクセスできます。だから、私がしたのは、このサービスからコンテキストオプションを取得し、必要なときにコンテキストを作成することです。長い生きているコンテキストは知らされておらず、エラーが発生した場合、DbContextはもはや使用できなくなります。最後に、websocketハンドラでDbContext自体を使用する代わりに、別のデータベースキャッシュレイヤを実装して書き込みました。

上記は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> 
    /// The options to create DbContexts with. 
    /// </summary> 
    DbContextOptions<AssemblyServerContext> ctxOpts; 

    /// <summary> 
    /// Constructor, assign socket to current instance and adds socket to ConnectedClients. 
    /// </summary> 
    /// <param name="socket"></param> 
    /// <param name="ctxOpts"></param> 
    WSHandler(WebSocket socket, DbContextOptions<AssemblyServerContext> ctxOpts) { 
     this.ctxOpts = ctxOpts; 
     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 ctxOptions = hc.RequestServices.GetService<DbContextOptions<AssemblyServerContext>>(); 
     var h = new WSHandler(socket, ctxOptions); 
     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 
      using (var ctx = new AssemblyServerContext(ctxOpts)) { 

      } 
     } 

    } 
} 
+0

ありがとう、私の夜は保存されています) – Mergasov

関連する問題