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()
DefaultDependencyResolver.GetServices
method, sinceIDependencyScope.GetServices
should never returnnull
, whileIServiceProvider.GetServices(Type)
will returnnull
when no registrations exist for the specifiedType
.DefaultDependencyResolver
bug, I fixed it