我正在使用ASP.NET Core 2.我试图将DbContext注入自定义的IRouteConstraint。但是,似乎在尝试调用Match方法之前处理了上下文。我确定我在这里忽略了一些非常简单的事情。我是如何将上下文传递给路径约束的?
public void ConfigureServices(IServiceCollection services)
{
...
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ApplicationDbContext applicationDbContext)
{
...
app.UseMvc(routes =>
{
// Route validation
routes.MapRoute("routevalidation", "{*route}", new { controller = "Home", action = "Reroute" }, new { route = new ShinyNewRouteConstraint() });
...
});
}
答案 0 :(得分:2)
这是一种方法(虽然不确定这是否是最好的方法):
public class ShinyNewRouteConstraint : IRouteConstraint
{
private readonly Func<ApplicationDbContext> createDbContext;
public ShinyNewRouteConstraint(Func<ApplicationDbContext> createDbContext)
{
this.createDbContext = createDbContext;
}
public bool Match(HttpContext httpContext, IRouter route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection)
{
using (var dbContext = createDbContext())
{
// Run a query...
var users = dbContext.Users.ToList();
// Constraint logic
}
return false;
}
}
// Route validation
routes.MapRoute(
"routevalidation",
"{*route}",
new { controller = "Home", action = "Reroute" },
new { route = new ShinyNewRouteConstraint(() =>
app.ApplicationServices.CreateScope().ServiceProvider.GetRequiredService<ApplicationDbContext>()) });
注意:我建议在此方案中使用缓存,因为每个请求都会匹配路由约束,这可能会使请求过多的数据库泛滥。