2016-12-08 71 views
3

我正在測試.net核心並使用.net core + websockets將一些小樣本應用程序推送到我的應用程序中。我想使用dbcontext將這些數據保存在數據庫中。.net核心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本身。

這裏是上面擴展的代碼來創建DbContexts。我沒有測試過,因爲現在我沒有可用的視覺工作室...

<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