Сбой привязки собственной сборки для решения ASP.NET

НОТА: Это основная цель вопросаПОНЯТЬ / EXPLAIN поведение привязки сборки CLR. Решение должно быть очевидным, как только причина будет определена. Пожалуйста, знайте, что я понимаю, что мои настройки не оптимальны (nativedll не подписаны, не имеют версий и т. Д.), Но опять же я просто хочу исследовать поведение привязки CLR.

Я пытаюсь использовать нативную (не COM, C ++) dll в моем решении asp.net. Я собираюсь воздержаться от именования DLL, потому что я думаю, что это отвлекает тему в неправильном направлении.

Нативная dll взята с сайта блога и не содержит много информации. У меня нет никакой информации о нативной dll-подобной архитектуре, на которой он был скомпилирован, о какой культуре и версии и т. Д. Используя предоставленную оболочку, я могу правильно использовать dll в консольном приложении. Это работает, хотя мы должны использоватьчастичное имя сборки для привязки. Оболочка для нативной сборки имеет импорт DLL как[DllImport("nativedll.dll")] public static extern void someMethod([Out] BE_VERSION pbeVersion);

Я прочитал много информации о привязке сборки CLR, включая:

Как среда выполнения находит сборки

Лучшие практики для сборки Загрузка

Насколько я понимаю, мы сможем загрузить сборку, но нет. Я получаю ошибки привязки сборки.



НАСТРОИТЬ



Моя вспомогательная библиотека (скомпилированная как MSIL (Любой ЦП)), которая вызывает родную DLLСильно назван и находится в GAC., Я запускаю свое приложение asp.net на 64-битной машине с Win 7 на IIS, а не на сервере разработки Visual Studio.Нативная DLL НЕ подписана и НЕ GACed.

ПРОБЛЕМА

Суть в том, что, когда я помещаю нативный DLL в каталог Windows, (c: \ Windows) решение работает нормально. В любом другом случае я получаю ошибки привязки сборки.



ВОПРОСЫ

1. Я хотел бы знать, почему сборка привязывается при удалении в каталог Windows? 2. Что означает ошибка: ошибка при извлечении импорта манифеста из файла (hr = 0x80131018)? (Посмотрите на Сценарий 1, Сценарий 6)

3. Почему происходит сбой вызова методов Assembly.Load * ()? (Сценарий 3, 4, 5)

РЕЗУЛЬТАТЫ МОЕГО ТЕСТИРОВАНИЯ



Сценарий 1:

**Setup**
Calling Assembly: GACed.
Native Assembly: Included in project; Build Action: None; Copy To Output Directory: Copy Always.

**Description:** 
Logged into the site, home page open. Did not navigate to the page with native call.

**Result:** 
    Binding Error
    *** Assembly Binder Log Entry  (12/13/2012 @ 11:28:23 AM) ***

        The operation failed.
        Bind result: hr = 0x80131018. No description available.

        Assembly manager loaded from:  C:\Windows\Microsoft.NET\Framework\v4.0.30319\clr.dll
        Running under executable  C:\Windows\SysWOW64\inetsrv\w3wp.exe
        --- A detailed error log follows. 

        === Pre-bind state information ===
        LOG: User = NT AUTHORITY\SYSTEM
        LOG: DisplayName = nativedll
         (Partial)
        WRN: Partial binding information was supplied for an assembly:
        WRN: Assembly Name: nativedll | Domain ID: 2
        WRN: A partial bind occurs when only part of the assembly display name is provided.
        WRN: This might result in the binder loading an incorrect assembly.
        WRN: It is recommended to provide a fully specified textual identity for the assembly,
        WRN: that consists of the simple name, version, culture, and public key token.
        WRN: See whitepaper http://go.microsoft.com/fwlink/?LinkId=109270 for more information and common solutions to this issue.
        LOG: Appbase = file:///C:/WebUI/
        LOG: Initial PrivatePath = C:\WebUI\bin
        LOG: Dynamic Base = C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\webui\69d9ded4
        LOG: Cache Base = C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\webui\69d9ded4
        LOG: AppName = ca4be085
        Calling assembly : (Unknown).
        ===
        LOG: This bind starts in default load context.
        LOG: Using application configuration file: C:\WebUI\web.config
        LOG: Using host configuration file: C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet.config
        LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
        LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind).
        LOG: Attempting download of new URL file:///C:/Windows/Microsoft.NET/Framework/v4.0.30319/Temporary ASP.NET Files/webui/69d9ded4/ca4be085/nativedll.DLL.
        LOG: Attempting download of new URL file:///C:/Windows/Microsoft.NET/Framework/v4.0.30319/Temporary ASP.NET Files/webui/69d9ded4/ca4be085/nativedll/nativedll.DLL.
        LOG: Attempting download of new URL file:///C:/WebUI/bin/nativedll.DLL.
        LOG: Assembly download was successful. Attempting setup of file: C:\WebUI\bin\nativedll.dll
        LOG: Entering download cache setup phase.
        ERR: Error extracting manifest import from file (hr = 0x80131018).
        ERR: Setup failed with hr = 0x80131018.
        ERR: Failed to complete setup of assembly (hr = 0x80131018). Probing terminated.    

Сценарий 2:

**Setup**
Scenario 1 + Just copy the nativedll to C:\Windows folder. No reset of anytype. 

**Description**
Navigate to the page calling native.

Result: 
Success. Native Functionality is invoked. No binding failure.

Сценарий 3:

**Setup**
Calling Assembly: GACed.
Native Assembly: Build Action: None; Copy To Output Directory: Copy Always.

Description: 
    Breakpoint at the point of native function call, use immediate window to execute the following code:

        var pat = pat = Path.Combine(AppDomain.CurrentDomain.RelativeSearchPath, "nativedll.dll");
        var a = Assembly.LoadFrom(pat);

    **Result**
    Exception raised:

    System.BadImageFormatException was unhandled
      HResult=-2146234344
      Message=Could not load file or assembly 'file:///C:\WebUI\bin\nativedll.dll' or one of its dependencies. The module was expected to contain an assembly manifest.
      Source=mscorlib
      FileName=file:///C:\WebUI\bin\nativedll.dll
      FusionLog=Assembly manager loaded from:  C:\Windows\Microsoft.NET\Framework\v4.0.30319\clr.dll
        Running under executable  C:\Windows\SysWOW64\inetsrv\w3wp.exe
        --- A detailed error log follows. 

        === Pre-bind state information ===
        LOG: User = NT AUTHORITY\SYSTEM
        LOG: Where-ref bind. Location = C:\WebUI\bin\nativedll.dll
        LOG: Appbase = file:///C:/WebUI/
        LOG: Initial PrivatePath = C:\WebUI\bin
        Calling assembly : (Unknown).
        ===
        LOG: This bind starts in LoadFrom load context.
        WRN: Native image will not be probed in LoadFrom context. Native image will only be probed in default load context, like with Assembly.Load().
        LOG: Using application configuration file: C:\WebUI\web.config
        LOG: Using host configuration file: C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet.config
        LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
        LOG: Attempting download of new URL file:///C:/WebUI/bin/nativedll.dll.
        ERR: Failed to complete setup of assembly (hr = 0x80131018). Probing terminated.

          StackTrace:
               at System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
               at System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
               at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
               at System.Reflection.RuntimeAssembly.InternalLoadFrom(String assemblyFile, Evidence securityEvidence, Byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm, Boolean forIntrospection, Boolean suppressSecurityChecks, StackCrawlMark& stackMark)
               at System.Reflection.Assembly.LoadFrom(String assemblyFile)
          InnerException: 

Сценарий 4:

**Setup**
    Calling Assembly: GACed.
    Native Assembly: Build Action: None; Copy To Output Directory: Copy Always.

**Description** 
    Breakpoint at the point of native function call, use immediate window to execute the following code:

    var pat = pat = Path.Combine(AppDomain.CurrentDomain.RelativeSearchPath, "nativedll.dll");
    var a = Assembly.Load(pat);

**Result**
    Exception raised:

        System.IO.FileLoadException was unhandled
          HResult=-2146234297
          Message=Could not load file or assembly 'C:\\WebUI\\bin\\nativedll.dll' or one of its dependencies. The given assembly name or codebase was invalid. (Exception from HRESULT: 0x80131047)
          Source=mscorlib
          FileName=C:\\WebUI\\bin\\nativedll.dll
          FusionLog=""
          StackTrace:
               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.Reflection.Assembly.Load(String assemblyString)
          InnerException: 

Сценарий 5:

**Setup**
Calling Assembly: GACed.
Native Assembly: Build Action: None; Copy To Output Directory: Copy Always.

**Description: **
    Breakpoint at the point of native function call, use immediate window to execute the following code:

    var pat = pat = Path.Combine(AppDomain.CurrentDomain.RelativeSearchPath, "nativedll.dll");
    var a = Assembly.LoadFile(pat);

    **Result**
    Exception raised:

        System.BadImageFormatException was unhandled
          HResult=-2146234344
          Message=The module was expected to contain an assembly manifest. (Exception from HRESULT: 0x80131018)
          Source=mscorlib
          StackTrace:
               at System.Reflection.RuntimeAssembly.nLoadFile(String path, Evidence evidence)
               at System.Reflection.Assembly.LoadFile(String path)
          InnerException: 

Сценарий 6:

**Setup**
Calling Assembly: GACed.
Native Assembly: Excluded from project. Manually copied into the bin folder prior to execution.

**Description: **
    Logged into the site, home page open. Did not navigate to the page with native call.

    **Result**
    Binding Error: (Output: Assembly Binding Log Viewer)

        Assembly Binder Log Entry  (12/13/2012 @ 2:19:13 PM)

        The operation failed.
        Bind result: hr = 0x80131018. No description available.

        Assembly manager loaded from:  C:\Windows\Microsoft.NET\Framework\v4.0.30319\clr.dll
        Running under executable  C:\Windows\SysWOW64\inetsrv\w3wp.exe
        --- A detailed error log follows. 

        === Pre-bind state information ===
        LOG: User = NT AUTHORITY\SYSTEM
        LOG: DisplayName = nativedll
         (Partial)
        WRN: Partial binding information was supplied for an assembly:
        WRN: Assembly Name: nativedll | Domain ID: 2
        WRN: A partial bind occurs when only part of the assembly display name is provided.
        WRN: This might result in the binder loading an incorrect assembly.
        WRN: It is recommended to provide a fully specified textual identity for the assembly,
        WRN: that consists of the simple name, version, culture, and public key token.
        WRN: See whitepaper http://go.microsoft.com/fwlink/?LinkId=109270 for more information and common solutions to this issue.
        LOG: Appbase = file:///C:/Web/WebUI/
        LOG: Initial PrivatePath = C:\WebUI\bin
        LOG: Dynamic Base = C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\webui\69d9ded4
        LOG: Cache Base = C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\webui\69d9ded4
        LOG: AppName = ca4be085
        Calling assembly : (Unknown).
        ===
        LOG: This bind starts in default load context.
        LOG: Using application configuration file: C:\WebUI\web.config
        LOG: Using host configuration file: C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet.config
        LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
        LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind).
        LOG: Attempting download of new URL file:///C:/Windows/Microsoft.NET/Framework/v4.0.30319/Temporary ASP.NET Files/webui/69d9ded4/ca4be085/nativedll.DLL.
        LOG: Attempting download of new URL file:///C:/Windows/Microsoft.NET/Framework/v4.0.30319/Temporary ASP.NET Files/webui/69d9ded4/ca4be085/nativedll/nativedll.DLL.
        LOG: Attempting download of new URL file:///C:/WebUI/bin/nativedll.DLL.
        LOG: Assembly download was successful. Attempting setup of file: C:\\WebUI\bin\nativedll.dll
        LOG: Entering download cache setup phase.
        ERR: Error extracting manifest import from file (hr = 0x80131018).
        ERR: Setup failed with hr = 0x80131018.
        ERR: Failed to complete setup of assembly (hr = 0x80131018). Probing terminated.

Сценарий 7:

**Setup**
Scenario 6 + Just copy the nativedll to C:\Windows folder. No reset of anytype. 

**Description**
Navigate to the page calling native.

Result: 
Success. Native Functionality is invoked. No binding failure.

Ответы на вопрос(1)

Ваш ответ на вопрос