我对c#和.NET颇为陌生,并试图创建一个动态加载程序集的asp.net web应用程序。c#.NET加载/卸载程序集,同时保持相同的会话
最初,我用Activator.CreateInstance
动态加载程序集,但它似乎锁定程序集DLL文件。因为我经常改变大会,所以变得非常痛苦。我还需要与其他应用程序共享程序集,因此稍后可能会成为问题。
看来,大多数人建议创建一个单独的AppDomain并将程序集加载到它中,然后在完成后卸载AppDomain。但是,我的应用程序和程序集也依赖于会话上下文,一旦将它发送到应用程序域,所有会话都会丢失;程序集崩溃,因为它找不到会话上下文。
有没有办法将我的会话上下文传递给AppDomain?或者有没有什么办法可以加载程序集而不锁定DLL文件?我尝试按照某些建议的流式传输文件,但它仍然锁定DLL。
编辑:我试过下面的代码为达维德Piras酒店建议,但DLL文件仍然锁定
private static T CreateInstance<T>(string fileName, string typeName)
{
if (!File.Exists(fileName)) throw new FileNotFoundException(string.Format("Cannot find assembly '{0}'.", fileName));
try
{
Assembly assembly = Assembly.LoadFrom(fileName);
if (assembly != null)
{
List<Type> assemblyTypes = assembly.GetTypes().ToList();
Type assemblyType =
assemblyTypes.FirstOrDefault(asmType => typeof(T).IsAssignableFrom(asmType));
T instance = (T) Activator.CreateInstance(assemblyType);
if (instance != null) return instance;
}
// Trouble if the above doesn't work!
throw new NullReferenceException(string.Format("Could not create type '{0}'.", typeName));
}
catch (Exception exp1)
{
throw new Exception("Cannot create instance from " + fileName + ", with type " + typeName + ": " + exp1.Message + exp1.Source, exp1.InnerException);
}
}
看到我的编辑和更多的代码就快到了:) –