2

I am using ASP.NET Core v1.1 to create a WebSocket server. This is a striped down version of my Startup.cs:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
  // ...

  // route of "/ws" requests
  app.Map("/ws", Map);
}


public void ConfigureServices(IServiceCollection services)
{
  // add the db service
  services.AddDbContext<ArticleContext>(
    opts => opts.UseNpgsql("MyConnectionString")
  );
}

private void Map(IApplicationBuilder app)
{
  app.UseWebSockets();
  app.Use(Acceptor);
}

private async Task Acceptor(HttpContext httpContext, Func<Task> next)
{
    // Handle the request using: httpContext.WebSockets.IsWebSocketRequest
    // ...
}

As you can see I am using an Acceptor task to handle the web socket requests. I also add a DbContext in the ConfigureServices method.

I do not add any MVC functionality since I am not using it. But I need to access the ArticleContext to connect to my database.

All examples that I have seen are using a Controller that comes with the MVC packages. In such a controller you can inject the DBContext using constructor dependency injection.

I do not use a Controller but the Acceptor method so how do I get the ArticleContext instance there?

Do I somehow have to write a MyAcceptor class and add it to the app via app.Use() instead of using app.Map to be able to inject dependencies? .. just a guess.

2
  • 1
    did you know that you can add any dependencies you need to the Configure method signature and they will be injected into the method so long as they were registered in ConfigureServices? Commented Dec 13, 2016 at 15:39
  • No I did not know it. Can be useful but does not solve my issue. Thank you for the comment. Commented Dec 13, 2016 at 16:11

1 Answer 1

5

You will have to resolve the ArticleContext from the HttpContext.RequestServices property as follows:

private async Task Acceptor(HttpContext httpContext, Func<Task> next)
{
    var context = httpContext.RequestServices.GetRequiredService<ArticleContext>();
    // Handle the request using: httpContext.WebSockets.IsWebSocketRequest
    // ...
}

You can also wrap the Acceptor method into a class of its own. In that case you can inject the ArticleContext into the constructor of that AcceptorMiddleware class, but this doesn't seem needed in your case.

Sign up to request clarification or add additional context in comments.

1 Comment

Seems to be exactly what I searched for. I wonder why I did not find such an example. Thank you Steven! I will try that as soon as possible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.