使用ApplicationHost.CreateApplicationHost()创建Asp.Net帖子,同时从其他位置加载程序集

时间:2010-07-13 12:00:38

标签: asp.net applicationhost

我正在尝试使用CreateApplicationHost为简单的Web服务器创建Asp.Net应用程序主机,但是当它尝试创建我的编组对象的实例时,我得到System.IO.FileNotFoundException

host = (MyMarshaller)ApplicationHost.CreateApplicationHost((MyMarshaller), virtualDir, physicalDir);

我相信这个错误是因为找不到包含MyMarshaller类的程序集 - 如果我将这个程序集放在physicalDir的bin目录中,那么一切正常,但是我不想这样做(我也不喜欢)我想将我的程序集放在GAC中。)

有什么方法可以控制CreateApplicationHost查找程序集的位置? (请注意,MyMarshaller类与上面的代码行在同一个程序集中进行了对比)

2 个答案:

答案 0 :(得分:4)

简短的回答是无法做到这一点,但是Cassini来源揭示了另一种解决方案。


<强>更新

上述链接不再有效,但CodePlex上的CassiniDev project似乎非常接近(可能是衍生作品),并且包含相同的解决方案。

解决方案是避免使用CreateApplicationHost和“自己动手” - 在这种情况下使用反射创建内部“BuildManagerHost”类型的实例并调用“RegisterAssembly”,如此

/// <remarks>
/// This is Dmitry's hack to enable running outside of GAC.
/// There are some errors being thrown when running in proc
/// </remarks>
private object CreateWorkerAppDomainWithHost(string virtualPath, string physicalPath, Type hostType,int port)
{
    // create BuildManagerHost in the worker app domain
    //ApplicationManager appManager = ApplicationManager.GetApplicationManager();
    Type buildManagerHostType = typeof(HttpRuntime).Assembly.GetType("System.Web.Compilation.BuildManagerHost");
    IRegisteredObject buildManagerHost = ApplicationManager.CreateObject(_appId, buildManagerHostType, virtualPath,
                                                                  physicalPath, false);

    // call BuildManagerHost.RegisterAssembly to make Host type loadable in the worker app domain
    buildManagerHostType.InvokeMember("RegisterAssembly",
                                      BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.NonPublic,
                                      null,
                                      buildManagerHost,
                                      new object[] { hostType.Assembly.FullName, hostType.Assembly.Location });

    // create Host in the worker app domain
    // FIXME: getting FileLoadException Could not load file or assembly 'WebDev.WebServer20, Version=4.0.1.6, Culture=neutral, PublicKeyToken=f7f6e0b4240c7c27' or one of its dependencies. Failed to grant permission to execute. (Exception from HRESULT: 0x80131418)
    // when running dnoa 3.4 samples - webdev is registering trust somewhere that we are not
    return ApplicationManager.CreateObject(_appId, hostType, virtualPath, physicalPath, false);
}

答案 1 :(得分:0)

How to load an assembly at runtime that is located in a folder that is not the bin folder of the application

如果不在GAC或BIN中,则必须使用Assembly.LoadFrom

Assembly SampleAssembly;
SampleAssembly = Assembly.LoadFrom("c:\\Sample.Assembly.dll");