【发布时间】:2011-09-08 20:35:47
【问题描述】:
我对 c# 和 .NET 比较陌生,并试图创建一个动态加载程序集的 asp.net Web 应用程序。
最初,我使用Activator.CreateInstance 动态加载程序集,但它似乎锁定了程序集 DLL 文件。因为我经常对组件进行更改,所以这变得相当痛苦。我还需要与其他应用程序共享程序集,所以以后可能会成为问题。
似乎大多数人建议创建一个单独的 AppDomain 并将程序集加载到其中,然后在我完成后卸载 appdomain。但是,我的应用程序和程序集也取决于会话上下文,一旦我将其发送到应用程序域,所有会话都会丢失;程序集崩溃,因为它找不到会话上下文。
有什么方法可以将我的会话上下文传递给 AppDomain?或者有什么方法可以让我在不锁定 DLL 文件的情况下加载程序集?我已经尝试按照一些建议流式传输文件,但它仍然锁定 DLL。
编辑:我已按照 Davide 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);
}
}
【问题讨论】:
-
查看我的编辑,更多代码即将推出 :)