I am trying to write something like an ObjectFactory which, given an assembly's path and a name of a type in that assembly, returns an instance of that same type using Reflection. Since I need to make this operations repeatedly for types in several different assemblies, should I use Assembly.LoadFrom everytime I need a new instance of a given type, or should I instead somehow cache the resulting Assembly object and a delegate to the type creation method?
-
1I don't know if this will benefit your performance enough, but even if it does you need to keep a close eye on the validity of your cache, ie it points to assembly files on disk, you may want to monitor those files and invalidate your cached reference if a file changesmtijn– mtijn2011-10-04 08:36:35 +00:00Commented Oct 4, 2011 at 8:36
2 Answers
No you don't need, if not by design decisions. You can hold a reference to the in memory assembly inside some Assembly type object.
Comments
Calling Assembly.LoadFrom every time would be a slow way to do it.
I would suggest that if you want to go down the path of building your own factory classes that you do cache Type instance for the classes you are activating.
Better yet I would suggest looking at dependency injection framework. If you are unfamiliar with dependency injection (DI) see http://en.wikipedia.org/wiki/Dependency_injection.
Most frameworks will at least provide object factories, type caching and will automatically resolve the constructor dependencies. This is great because you don't have to re-invent the wheel and you can reuse the same methodology in all you application if you like.
If you are purposely going through the process of building an object factory then I would suggest that you take a look at these open source implementations anyway because they are great examples of how DI works well.
Unity Application Block - http://unity.codeplex.com/
StructureMap - http://structuremap.sourceforge.net/Default.htm
CastleWindsor - http://www.castleproject.org/container/index.html
Ninject - http://ninject.org/