Reputation: 9051
I'm working on a component which executes provisional method of any interface registered with ioc, and execution moment depends on different triggers. It must be able to save actions to be performed to database, so I'm saving method name, type and list of parameters (serialized to BLOB) into database until needed.
When trigger occurs, I need to execute method on a instance of type. As I'm using dependency injection, I have interface name saved into database (in format "Namespace.IInterface, AssemblyName"
)
To run Resolve<IInterface>()
method on ioc container, I need instance of its Type
:
Assembly assembly = System.Reflection.Assembly.Load(assemblyName);
Type service = assembly.GetType(typeName);
object instance = IOCContainer.Resolve(service);
My questions are:
Type.Load(typeName)
but got null)Upvotes: 5
Views: 4491
Reputation: 151
To verify performance impact, I tried loading same assembly for n times. And found total allocated memory growing with each call.
while (true)
{
Assembly assembly = Assembly.LoadFrom("abc.dll");
//monitor: AppDomain.CurrentDomain.MonitoringTotalAllocatedMemorySize
//memory growing with each call
}
=============
Then I did this to make sure I am loading assembly only once.
var typeName = "Namespace.ClassName, Namespace";
while (true)
{
var typeFound = Type.GetType(typeName);
if (typeName == null)
{
Assembly assembly = Assembly.LoadFrom("abc.dll");
}
//monitor: AppDomain.CurrentDomain.MonitoringTotalAllocatedMemorySize
//memory will not grow after first call
}
Upvotes: 2
Reputation: 9051
If assembly in question is already loaded, will CLR optimize that process (use already loaded)
Answer to just this question is on step 2 of MSDN article How the Runtime Locates Assemblies:
If the requested assembly has also been requested in previous calls, the common language runtime uses the assembly that is already loaded. This can have ramifications when naming assemblies that make up an application. For more information about naming assemblies, see Assembly Names.
Not directly related to the question, but also useful:
If a previous request for the assembly failed, subsequent requests for the assembly are failed immediately without attempting to load the assembly. Starting with the .NET Framework version 2.0, assembly binding failures are cached, and the cached information is used to determine whether to attempt to load the assembly.
Upvotes: 2
Reputation: 4577
typeName
that you use includes assembly name(something like MyNamespace.MyType, MyAssembly version=1.0.0.0,publicKeyToken=12345etc
) then Type.Load(typeName)
will get your type but not null;Upvotes: 5
Reputation: 5832
Is there a better way to get an instance of Type from its name, if I'm sure that containing assembly is already loaded into app domain? (I tried with simply Type.Load(typeName) but got null)
No.
If assembly in question is already loaded, will CLR optimize that process (use already loaded)
Yes.
Each assembly is loaded only once.
Upvotes: 3