21

I have a service I wrote that helps with configuration. The service is set up in the Startup class's ConfigureServices method as:

public void ConfigureServices(IServiceCollection services)
{
    ...

    services.AddScoped<IMyService, MyService>();

    ...
}

I need to then get an instance of IMyService in the Startup class's Configure method. How do I do that?

Pang
  • 9,564
  • 146
  • 81
  • 122
David Derman
  • 821
  • 2
  • 9
  • 19

1 Answers1

31

Since you've already added your service with AddScoped, all you need to do is add another parameter to the Configure method with the correct type and the dependency injection system will take care of it for you:

public void Configure(IApplicationBuilder app, 
    IHostingEnvironment env, 
    ILoggerFactory loggerFactory, 
    IMyService myService)
{
    //Snip
}
DavidG
  • 113,891
  • 12
  • 217
  • 223
  • 12
    I also figured out I can instantiate it with "var myservice = App.ApplicationServices.GetService();". I think your answer is better though. :) – David Derman Mar 15 '17 at 16:31