Could not resolve a service of type 'IMyService' for the parameter 'mySvc' of method 'Configure' on type 'Startup'
I am moving my project from asp.net5 beta 4 to beta 5.
Below is an example of ConfigureServices method in Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IMyService, MyService>();
}
And this is Configure method in Startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IMyService mySvc)
{
}
In beta 4 dependency injection used to work okay and I could use myService in side Configure method.
Now i am getting an error:
Could not resolve a service of type 'IMyService' for the parameter 'mySvc' of method 'Configure' on type 'Startup
at Microsoft.AspNet.Hosting.Startup.ConfigureBuilder.Invoke(Object instance, IApplicationBuilder builder)
at Microsoft.AspNet.Hosting.Startup.ConfigureBuilder.<>c__DisplayClass4_0.<Build>b__0(IApplicationBuilder builder)
at Microsoft.AspNet.Hosting.Internal.AutoRequestServicesStartupFilter.<>c__DisplayClass0_0.<Configure>b__0(IApplicationBuilder builder)
at Microsoft.AspNet.Loader.IIS.RuntimeHttpApplication.HeliosStartupFilter.<>c__DisplayClass0_0.<Configure>b__0(IApplicationBuilder builder)
at Microsoft.AspNet.Hosting.Internal.HostingEngine.BuildApplication()
at Microsoft.AspNet.Hosting.Internal.HostingEngine.Start()
at Microsoft.AspNet.Loader.IIS.RuntimeHttpApplication.ApplicationStart(IHttpApplication application)
at Microsoft.AspNet.Loader.IIS.HttpApplicationBase.InvokeApplicationStart(IHttpApplication application)
You can get your service from application services, like this
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
IMyService service = app.ApplicationServices.GetService<IMyService>();
}
or changing Configure method signature to this
public void Configure(IApplicationBuilder app, IHostingEnvironment env,
ILoggerFactory loggerFactory, IMyService service)
{
}
or even changing your DI configuration to
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<MyService>();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, MyService mySvc)
{
}
Your are registering a service as IMyService, but then you are trying to consume it as MyService. If you change your Configure method to take an IMyService it should work.
Please note that this question is not specific to MVC. For general DI questions you can file issues in the Dependency Injection repo.
Yes this isn't a bug, even better would be to ask general question on aspnet/Home
Thank you for your guidance :+1: