0

I'm trying to add a parameter to the constructor of the Startup class in Asp.net core using this method: https://mattmazzola.medium.com/asp-net-core-injecting-custom-data-classes-into-startup-classs-constructor-and-configure-method-7cc146f00afb

However, this doesn't work for me. Here's my C# Code:

public class AppAProgram
{
    #region Members
    private IHostBuilder hostBuilder;

    private IHost host;
    #endregion

    #region Constructors
    public AppAProgram(string[] args)
    {
        this.hostBuilder = Host.CreateDefaultBuilder(args);
        ILauncherContext launcherContext = new DummyLauncherContext();
        this.hostBuilder.ConfigureServices((hostContext, services) => { services.AddSingleton<ILauncherContext>(launcherContext); });
        this.hostBuilder.ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<AppAStartup>(); });
        this.host = hostBuilder.Build();
    }
    #endregion

    public static void Main(string[] args)
    {
        AppAProgram appAProgram = new AppAProgram(args);    
        appAProgram.Start();
    }

    public void Start()
    {
        this.host.Run();
    }
}

Here's the constructor for which I add an injected parameter:

    #region Constructors
    public AppAStartup(IConfiguration configuration, ILauncherContext launcherContext)
    {
        Configuration = configuration;
        this.launcherContext = launcherContext;
    }
    #endregion

When I do this, I get this exception:

System.InvalidOperationException: 'Unable to resolve service for type 'Spike.Run.Launcher.ILauncherContext' while attempting to activate 'Spike.Run.AppA.AppAStartup'.'

evg02gsa3
  • 571
  • 5
  • 17
  • while injecting dependencies into the Startup's constructor is something funny to play, do you have an actual reason why you want that? Any possible scenarios for that? – King King Jan 14 '21 at 20:37
  • Shouldn't you use `services.AddSingleton()` to add the dependency? Instead of creating the object yourself. – JHBonarius Jan 14 '21 at 20:39

1 Answers1

2

Reference The Startup class

Only the following service types can be injected into the Startup constructor when using the Generic Host (IHostBuilder):

  • IWebHostEnvironment
  • IHostEnvironment
  • IConfiguration

...

Most services are not available until the Configure method is called.

emphasis mine

Use the Configure method instead

public AppAStartup(IConfiguration configuration) {
    Configuration = configuration;        
}

public void Configure(IApplicationBuilder app, ..., ILauncherContext launcherContext) {

    //access launcherContext here

    //...
}
Nkosi
  • 235,767
  • 35
  • 427
  • 472