Luca Hofmann
Luca Hofmann

Reputation: 1522

Creating middleware function with dependency in ASP.NET Core

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.

Upvotes: 2

Views: 1719

Answers (1)

Steven
Steven

Reputation: 172616

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.

Upvotes: 5

Related Questions