Once loaded an assembly can't be unloaded (unless you unload the full AppDomain that loaded it) (see for example How to unload an assembly from the primary AppDomain?). So there is the opposite problem of yours :-)
Now... You can surely speed up everything:
Type myType = Type.GetType("MyAssembly.MyClass, MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=1r46a5dfa04dase2");
This call will need to be executed every time. While the assembly won't be loaded, a search in the assembly will be done. You can cache myType
.
var myObject = Activator.CreateInstance(myType) as IMyClass;
This will search for a parameterless constructor for myType
every time. You could speed up this by caching the constructor (myConstructor
) you need:
ConstructorInfo myConstructor = myType.GetConstructor(Type.EmptyTypes);
var myObject = myConstructor.Invoke(null) as IMyClass;
Now... Even using reflection is slow... you could create a dynamic method that invokes the constructor and cache it:
Func<IMyClass> myCreate = Expression.Lambda<Func<IMyClass>>(Expression.New(myConstructor)).Compile();
var myObject = myCreate();
So in the end you could cache only myCreate
:-)