I am trying to write something like an ObjectFactory
which, given an a开发者_运维百科ssembly'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?
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.
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/
精彩评论