Trying to built menu from MenuHelperModel
causes MvcSiteMap to construct all my controllers. That could be a big performance hit.
Is this only way to go when I rely on [Authorize]
to set up security for controllers?

- 55,572
- 24
- 139
- 212

- 1,040
- 7
- 23
1 Answers
First of all, constructors should be simple. If creating your controllers on each request is slowing your application down, it is a sign that your constructors are doing too much work. The MVC framework creates one instance per request, anyway, so this is likely slowing down more than just MvcSiteMapProvider
.
That said, there is another option. You can use the roles attribute/Roles property to set the same roles as you have in AuthorizeAttribute. The downsides of doing this are:
- You have to duplicate your entire security scheme.
- You won't be able to use a custom AuthorizeAttribute.
You might be able to work around the first limitation by making a dynamic node provider that scans your application using Reflection and sets up the roles from AuthorizeAttribute as the roles of the corresponding node. This code is only run once per cache timeout, so having some Reflection at that point probably won't cause a performance problem.

- 55,572
- 24
- 139
- 212
-
1>The MVC framework creates one constructor instance per request, anyway. One instance per request is not same as one instance per controller per request, but I understand your point. Getting my constructors simpler was my first step. – Leotsarev Feb 02 '17 at 07:20
-
1True. But unfortunately, Microsoft didn't have the foresight for anyone who wants to use `AuthorizeAttribute` for checking security on anything that is *not* the current request - you are left with no choice but to mock up a `ControllerContext` object that represents the *would be* request, which requires a controller instance (or duplicate the whole security scheme as I mentioned). – NightOwl888 Feb 02 '17 at 08:39