question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Request: allow dependency injection in RouteConstraints and IRouter

See original GitHub issue

Hi,

Problem

Currently, the registration of IRoute and IRouteConstraint implementations is not adapted for dependency injection. In order to add implementations of those, one needs to explicitly initialize them. My request is that you allow registering them so that they are resolved by the container when required.

For instance, I’m working on a multi-tenant app, and I want to make sure tenant exists before we’re routing to controller etc. There is a catalog database containing the tenant info, and I’d want to break the routing if the tenant doesn’t exist in the catalog DB.

Solution

My request is that allow ‘registering’ IRouteContraints implementations so that they are resolved by the DI container, instead of registering their type in the dictionary. For example:

// Startup.cs
public void ConfigureServices(IServiceCollection services)
{     
      services.Configure<RouteOptions>(options => {
        // suggested:
        options.ConstraintMap.Register<SubdomainConstraint>();
      });
}

// SubdomainConstraint.cs

public class SubdomainConstraint : IRouteConstraint
  {
    // this provider uses the CatalogDbContext to check if tenant exists
    readonly ITenantProvider _TenantProvider;

    public SubdomainConstraint(ITenantProvider tenantProvider)
    {
      _TenantProvider = tenantProvider;
    }

    public bool Match(HttpContext httpContext, IRouter route, string routeKey,
         RouteValueDictionary values, RouteDirection routeDirection)
    {
      return _TenantProvider.Tenant != null;
    }
}

The same applies to IRouter:

// Startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{     
    app.UseMvc(routes =>
    {
        routes.Routes.Register<SubdomainRouter>();
    });
}

// SubdomainRouter.cs

public class SubdomainRouter : IRouter
{
  readonly IRouter _DefaultRouter;
  readonly ITenantProvider _TenantProvider;

  public SubdomainRouter(IRouter defaultRouter, ITenantProvider tenantProvider)
  {
    _DefaultRouter = defaultRouter;
    _TenantProvider = tenantProvider;
  }

  public VirtualPathData GetVirtualPath(VirtualPathContext context) => 
      _DefaultRouter.GetVirtualPath(context);

  public Task RouteAsync(RouteContext context)
  {
    if (_TenantProvider.Tenant == null)
      context.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;

    return _DefaultRouter.RouteAsync(context);
  }
}

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:10 (6 by maintainers)

github_iconTop GitHub Comments

1reaction
mkArtakMSFTcommented, May 29, 2019

@rynowak do we have a mechanism to achieve this?

0reactions
rynowakcommented, May 30, 2019

Right. These have to be singletons.

If you want to participate in the request scope, use HttpContext.RequestServices to retrieve what you need.

Read more comments on GitHub >

github_iconTop Results From Across the Web

ASP.NET MVC Custom Route Constraints, Dependency ...
@BenFoster, in my case I'm building a multi-tenant app and need to validate that current subdomain is mapped to an existing tenant in...
Read more >
How to create route constraints in ASP.NET Core
IRouter – represents the router that will apply the constraints. RouteKey – represents the route parameter that is being validated.
Read more >
Routing in ASP.NET Core
Discover how ASP.NET Core routing is responsible for matching HTTP requests and dispatching to executable endpoints.
Read more >
More migration scenarios
Dependency injection is built into .NET Core itself. All of this can be configured in Program.cs, as is shown in the eShopPorted app...
Read more >
ASP.NET Core Anatomy (Part 4) - Invoking the MVC Middleware
So, let's begin and look at how MVC matches a request through to an available route and finally to an action which can...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found