2

I am trying to add Microsoft Extensions Dependency Injection to an existing ASP.NET WebApi/Owin project.

Following this blog post, I have added the ConfigureServices function, implemented DependencyResolver, and made HttpConfiguration instance to use it.

Also I added all the non-abstract controllers to DI, and ensured they are instantiated using the DI mechanism.

But after all these actions, requests to the application return error 500 with exception

Method not found: 'System.Net.Http.HttpRequestMessage System.Web.Http.Controllers.HttpActionContext.get_Request()'.

I get the same result even if I just add the Microsoft.Extensions.DependencyInjection package to NuGet and don't change any other code. After I remove it, everything works fine.

Here is the code I added into Startup.cs:

The DependcyResolver implementation:

public class DefaultDependencyResolver :
    System.Web.Http.Dependencies.IDependencyResolver, 
    System.Web.Http.Dependencies.IDependencyScope
{
    protected IServiceProvider serviceProvider;

    public DefaultDependencyResolver(IServiceProvider serviceProvider)
    {
        this.serviceProvider = serviceProvider;
    }

    public IDependencyScope BeginScope()
    {
        return this;
    }

    public void Dispose() { }

    public object GetService(Type serviceType)
    {
        return this.serviceProvider.GetService(serviceType);
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        return this.serviceProvider.GetServices(serviceType);
    }

}

Adding controllers to DI:

public void ConfigureServices(IServiceCollection services)
{
    System.Diagnostics.Debugger.Launch();   
    IEnumerable<Type> controllers = typeof(Startup).Assembly.GetExportedTypes()
       .Where(t => !t.IsAbstract && !t.IsGenericTypeDefinition)
       .Where(t => typeof(IController).IsAssignableFrom(t)
          || t.Name.EndsWith("Controller", StringComparison.OrdinalIgnoreCase));

    foreach (var c in controllers)
    {
        services.AddTransient(c);
    }
}

Creating ServiceCollection, calling services configuration and setting DependencyResolver:

public void Configuration(IAppBuilder app) {
    // ...
    HttpConfiguration httpConfiguration = new HttpConfiguration();

    var services = new ServiceCollection();
    ConfigureServices(services);

    httpConfiguration.DependencyResolver = 
        new DefaultDependencyResolver(services.BuildServiceProvider());

    WebApiConfig.Register(httpConfiguration);
    app.UseWebApi(httpConfiguration);
}

The exception stacktrace:

at myCompany.myProduct.Controllers.SomeController.Get(String id, String offline)
at lambda_method(Closure , Object , Object[] )
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters)
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n
System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()
4
  • Always post the full stack trace of the exception and its inner exceptions.
    – Steven
    Oct 23, 2017 at 11:33
  • 1
    Also note that there is a bug in your DefaultDependencyResolver.GetServices method, since IDependencyScope.GetServices should never return null, while IServiceProvider.GetServices(Type) will return null when no registrations exist for the specified Type.
    – Steven
    Oct 23, 2017 at 11:46
  • Please add information such as the stack trace, message and exception type of all the inner exceptions as well.
    – Steven
    Oct 23, 2017 at 12:10
  • @Steven I would like to give you more, but due to complicated debug process, that's all exception information I can post. Also, thanks for pointing DefaultDependencyResolver bug, I fixed it
    – alex.k
    Oct 24, 2017 at 7:56

2 Answers 2

3

You might need to add binding redirects to your web.config file. Check the following links with more information on the issue:

https://github.com/Microsoft/BotBuilder/issues/3615

https://github.com/dotnet/standard/issues/481

https://learn.microsoft.com/en-us/dotnet/framework/configure-apps/how-to-enable-and-disable-automatic-binding-redirection

2

I've installed 'System.Net.Http' from nuget (v 4.3.3) and updated my .csproj file to force msbuild to use specified dll:

<Reference Include="System.Net.Http, Version=4.1.1.2, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
  <HintPath>..\packages\System.Net.Http.4.3.3\lib\net46\System.Net.Http.dll</HintPath>
</Reference>

It resolved the problem.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.