I do web. service that load assembly file by input parameter. Then in assembly will try to find a specific type (inherited from specific interface), create an instance and returns the result of the method.
I need to make the call to the assembly was again released.
From the input parameters of the method I find the path to the the assembly in web.config. and try to load it.
This is the code that works:
[WebMethod]
public String[] GetData(String confKey)
{
var assemblyPath = ConfigurationManager.AppSettings[confKey];
var assembly = Assembly.LoadFrom(assemblyPath);
List<String> retVals = new List<String>();
foreach (var t in assembly.GetTypes())
{
if (t.ImplementsInterface(typeof(IMyServiceProvider)))
{
IMyServiceProvider objectInstance = Activator.CreateInstance(t) as IMyServiceProvider;
retVals.Add(objectInstance.GetData());
}
}
return retVals.ToArray();
}
But this way I can delete the loaded assembly or replace it because the file is "locked".
So I tried to go a different way and load the assembly into own AppDomain like this:
[WebMethod]
public String[] GetData(String confKey)
{
var assemblyPath = ConfigurationManager.AppSettings[confKey];
var tmp = String.Concat("AppDomain", Guid.NewGuid().ToString("N"));
AppDomain dom = AppDomain.CreateDomain(tmp, null, AppDomain.CurrentDomain.SetupInformation);
AssemblyName assemblyName = new AssemblyName();
assemblyName.CodeBase = assemblyPath;
Assembly assembly = dom.Load(assemblyPath);
List<String> retVals = new List<String>();
foreach (var t in assembly.GetTypes())
{
if (t.ImplementsInterface(typeof(IMyServiceProvider)))
{
IMyServiceProvider objectInstance = Activator.CreateInstance(t) as IMyServiceProvider;
retVals.Add(objectInstance.GetData());
}
}
AppDomain.Unload(dom);
return retVals.ToArray();
}
But this solution is thrown Exception:
Could not load file or assembly 'NameOfMyAssembly' or one of its dependencies. The given assembly name or codebase was invalid. (Exception from HRESULT: 0x80131047)- at System.Reflection.AssemblyName.nInit(RuntimeAssembly& assembly, Boolean forIntrospection, Boolean raiseResolveEvent) at System.Reflection.RuntimeAssembly.CreateAssemblyName(String assemblyString, Boolean forIntrospection, RuntimeAssembly& assemblyFromResolveEvent) at System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean forIntrospection) at System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) at System.AppDomain.Load(String assemblyString) at System.AppDomain.Load(String assemblyString)
Why the first solution assembly loads without problem, and the second throws an error ? Thanks