1

I'm working in an ASP.NET MVC 4 application, and on app start up I'm looking using BuildManager to get all referenced assemblies.I'm looking through all types in the application to find a few that I want (it's dynamic so I don't know what types I need until start up).

Essentially my code looks like this:

var allTypes = BuildManager.GetReferencedAssemblies()
                  .Cast<Assembly>()
                  .SelectMany(a => a.GetTypes());

I'm calling this on app startup but also at the beginning of each new request in order to dynamically find types.

So my questions are:

  1. Since ASP.NET doesn't load assemblies until they're needed, by calling BuildManager.GetReferencedAssemblies() am I loading ALL assemblies before they're needed and causing a performance issue?
  2. Is iterating through all types a bad idea for each request? I could cache the types but ASP.NET has the option of loading assemblies dynamically after I've cached them, right? If so I may miss some types which are indeed there.

Thanks!

Jens Björnhager
  • 5,632
  • 3
  • 27
  • 47
JonH
  • 821
  • 11
  • 19

1 Answers1

1

Don't do it every request: do cache as early as possible; reflection is slow.

Pre-load all the assemblies and do it on app-startup; I have a system that I use in a lot of our websites which has to do a lot of dynamic stuff based on deployed assemblies, and I do all the work on startup.

Yes startup is therefore slower - but that's less of a problem than each request taking longer.

You will then most likely be interested in a question I asked and answered a while ago about how to preload all deployed assemblies reliably: How to pre-load all deployed assemblies for an AppDomain.

I still use the same process to this day and it works like a charm.

Community
  • 1
  • 1
Andras Zoltan
  • 41,961
  • 13
  • 104
  • 160
  • Thanks! It seems as if `BuildManager.GetAllAssemblies()` loads everything - even dynamic assemblies. So if I iterate through that at start up and cache the results, would this effectively be "preloading" so I don't have to do it manually? – JonH Aug 30 '12 at 15:47
  • It would appear that for websites that is indeed the case, so yes you should be able to rely on that to get all the deployed assemblies for a website. If you iterate them and start interrogating them then definitely yes it will pre-load them (to a point, the JIT will still only do in-memory compilation of what's needed, when it's needed). – Andras Zoltan Aug 30 '12 at 15:54