I'm trying to inject my own classes using dependency injection, like this:
// Startup.cs
public class Startup
{
private readonly ILogger _log;
private readonly IMainController _controller;
public Startup(ILoggerFactory loggerFactory, IMainController controller)
{
_log = loggerFactory.CreateLogger("Logger");
_controller = controller;
}
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IMainController, MainController>();
// services.AddTransient<MainController, MainController>();
}
and then MainController, the object to be injected
// MainController.cs
public interface IMainController
{
Task Run(HttpContext context);
}
public class MainController : IMainController
{
private readonly ILogger _log;
public MainController(ILoggerFactory loggerFactory)
{
_log = loggerFactory.CreateLogger("Logger");
}
At runtime, I get the following error:
Unhandled Exception: System.InvalidOperationException: Unable to resolve service for type 'mtss.ws.IMainController' while attempting to activate 'mtss.ws.Startup'. at Microsoft.Extensions.Internal.ActivatorUtilities.ConstructorMatcher.CreateInstance(IServiceProvider provider) at Microsoft.Extensions.Internal.ActivatorUtilities.CreateInstance(IServiceProvider provider, Type instanceType, Object[] parameters)
I want to inject an ILoggerFactory in MainController (as it's doing in Startup) and then inject a newly created MainController in Startup...
According to documentation, you should note the following
You are trying to resolve a service that is not available when the constructor of
Startup
is called.IMainController
is not registered as yet when the constructor is called. however, It should be available by the timeConfigure
is called, allowing an opportunity to inject your custom service because it is called afterConfigureServices
and as of RTM, a scoped service provider will be created for theConfigure
method.The above should work in .net-core 2.0