我正在对我在MVC5中编写的自定义CMS进行大规模改革。此自定义CMS具有"页面"有" urls"存储在数据库中。例如,如果用户在浏览器中请求/ stackoverflow并且数据库中有一个页面,其中/ stackoverflow被列为url,那么我将在特定的CoreCms / Index Controller上提供数据库内容,并以数据库内容作为模型进行查看属性。我的想法是,我可以使用这个单一的控制器/视图来提供数据库中的任何页面。
我正在使用的重写仅在服务层中使用依赖注入和异步调用。看来我在使用RouteConfig RegisterRoutes静态方法时遇到了一些麻烦。
这里有一些代码......
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("FileBrowser/{pathInfo}");
routes.MapRoute(
name: "CmsRoutes",
url: "{*permalink}",
defaults: new { controller = "CmsCorePage", action = "Index" },
constraints: new { url = new CmsCoreRouting() }
);
routes.MapRoute(
name: "ArticlesCategoryRoute",
url: "Articles/{categoryURL}",
defaults: new { controller = "CmsCoreArticles", action = "Index", categoryURL = UrlParameter.Optional }
);
routes.MapRoute(
name: "ArticlesPostsRoute",
url: "Articles/{categoryURL}/{postURL}",
defaults: new { controller = "CmsCoreArticles", action = "ArticlePost", categoryURL = UrlParameter.Optional, postURL = UrlParameter.Optional }
);
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
请注意,我正在重写旧代码和约束:new {url = new CmsCoreRouting()}是我打算在这里改变的代码我相信。
供参考,这是CmsCoreRouting类......
public class CmsCoreRouting : IRouteConstraint
{
private ICoreCmsServices _coreSvc;
public CmsCoreRouting()
{
}
public CmsCoreRouting(ICoreCmsServices coreSvc)
{
_coreSvc = coreSvc;
}
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
if (httpContext?.Request?.FilePath == null) { return false; }
string myURL = httpContext.Request.FilePath;
if (myURL.StartsWith("/"))
{
myURL = myURL.Substring(1, myURL.Length - 1);
}
myURL = myURL.ToLower();
var siteId = CoreCms.Core.Settings.CoreCmsSettings.SiteId;
var cmsPage = AsyncUtility.RunSync(() => _coreSvc.PageService.FindBySiteAndUrlAsync(siteId, myURL));
if (cmsPage != null)
{
return true;
}
var cmsArticle = AsyncUtility.RunSync(() => _coreSvc.ArticleService.FindCategoryBySiteAndUrlAsync(siteId, myURL));
if (cmsArticle != null)
{
return true;
}
return false;
}
}
问题:当MVC启动时,它会调用CmsCoreRouting上的无参数构造函数(因为我在url = new CmsCoreRouting()中告诉它)但我不知道如何使用AutoFac的DI以便我不要&# 39;必须在此RegisterRoutes函数上传递我自己的服务和存储库实例以及DbContext。
对此的任何帮助都会很棒。我想这样做"对"。
答案 0 :(得分:1)
请让解析器(AutoFac)为您创建:
routes.MapRoute(
name: "CmsRoutes",
url: "{*permalink}",
defaults: new { controller = "CmsCorePage", action = "Index" },
constraints: new { url = DependencyResolver.Current.GetService<CmsCoreRouting>() }
);