I am trying to instruct my ASP.NET Core MVC application to use a 3rd party DI container. Rather than writing an adapter I am trying to just plug in the the library following the advice in this post
This works pretty well - I can replace the built in IControllerActivator
with my own that uses the DI container. However, I am running into a roadblock when trying to instantiate custom middleware that also relies on injected dependencies. ASP.NET cannot resolve these dependencies because it is not using my 3rd party DI container - is there an equivalent of IControllerActivator
for middleware, or am I stuck using the built-in DI or writing an adapter?
** EDIT **
Here's some more of my code - I am actually trying to use Ninject using the pattern above.
internal sealed class NinjectControllerActivator : IControllerActivator
{
private readonly IKernel _kernel;
public NinjectControllerActivator(IKernel kernel)
{
_kernel = kernel;
}
[DebuggerStepThrough]
public object Create(ActionContext context, Type controllerType)
{
return _kernel.Get(controllerType);
}
}
I've discovered I have two problems:
- I can't inject standard ASP.NET components into my controllers because Ninject is not aware of them
- My middleware that uses application services can't be instantiated because ASP.NET isn't aware of Ninject.
For an example of the first problem, here's a controller that fails to instantiate because I'm using IUrlHelper
(also note the ILogger
, which also fails to instantiate):
public class SystemController : Controller
{
public SystemController(ILogger logger, IUrlHelper urlHelper)
{
/*...*/
}
}
Here's an example of the second problem with a custom middleware:
public class CustomMiddleware
{
private RequestDelegate _next;
// this is an application specific service registered via my Ninject kernel
private IPersonService _personService;
public CustomMiddleware(RequestDelegate next, IPersonService personService)
{
_next = next;
_personService = personService;
}
public async Task Invoke(HttpContext context)
{
/* ... */
}
}
I realize that in theory ASP.NET components should be in their own pipeline and my application components should be in another, but in practice I often need to use components in a cross-cutting way (as in the examples above).