Ошибка разрешения зависимостей простого инжектора - не удалось загрузить файл или сборку System.Web.Http

Я следую за луковой архитектурой и использую simple injector в проекте DependencyResolution. Вот моя архитектура:

1-Core
     - Domain Classes
     - Repository Interfaces
     - Service Interfaces
2-Infrastructure
     - Data
     - Dependency Resolution
     - Repository Interfaces Implementation
     - Service Interfaces Implementation
3-WebApi
     - Web Api Project
4-WebClient
     - My AngularJs App
5-Test
     - Test Project

StartUp.cs

public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // Here I am getting error at runtime.
            SimpleInjectorInitializer.Initialize(app);
            ConfigureAuth(app);
        }
    }

SimpleInjectorInitializer.Initialize

public static Container Initialize(IAppBuilder app)
        {
            var container = GetInitializeContainer(app);

            // This is an extension method from the integration package.
            container.RegisterWebApiControllers(GlobalConfiguration.Configuration);

            container.Verify();

            GlobalConfiguration.Configuration.DependencyResolver =
                new SimpleInjectorWebApiDependencyResolver(container);

            return container;
        }

Здесь я добавил ссылку на System.Web, System.Web.Http, System.Web.Http.Host взято из проекта WebApi.

Я положил путь вывода моего проекта DependencyResolution в бин WebApi и установил значение owinstart в web.config,

Вот ошибка, которую я получаю:

Исключение типа "System.IO.FileLoadException" возникло в Infrastructure.DependencyResolution.dll, но не было обработано в коде пользователя

Дополнительная информация: Не удалось загрузить файл или сборку 'System.Web.Http, версия =4.0.0.0, Culture= нейтральный, PublicKeyToken=31bf3856ad364e35' или одну из ее зависимостей. Определение манифеста обнаруженной сборки не соответствует ссылке на сборку. (Исключение из HRESULT: 0x80131040)

Редактировать:

Вот App.Config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
  </configSections>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security.Cookies" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

2 ответа

Решение

Возможно, вам не хватает перенаправления привязки в файле конфигурации приложения. В большинстве случаев менеджер пакетов NuGet правильно установит перенаправления привязки, поскольку иногда этого не происходит.

Перенаправление привязки, которое вам нужно в вашем конфигурационном файле, выглядит следующим образом:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" 
            culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-{version}" newVersion="{version}"/>
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

Обратите внимание, что вам нужно заменить {version} заполнители для актуальной версии, на которую вы ссылаетесь.

Вы уверены, что используете ту же версию SimpleInjector во всех проектах, которые вы использовали Dependency Injection? Я столкнулся с похожей ошибкой и заметил, что старая версия SimpleInjectors используется в одном проекте. Он начал работать после того, как я обновил SimpleInjector nuget до новой версии.

Другие вопросы по тегам