ASP.Net Core MVC Dependency Injection not working

前端 未结 3 510
时光说笑
时光说笑 2020-12-14 02:27

I am trying to inject a interface into to my HomeController and I am getting this error:

InvalidOperationException: Unable to resolve service for type

相关标签:
3条回答
  • 2020-12-14 02:32

    Try injecting it as an IConfigurationRoot instead of IConfiguration:

     public HomeController(IConfigurationRoot configuration
        , IEmailSender mailService)
    {
        _mailService = mailService;
        _to = configuration["emailAddress.Support"];
    }
    

    In this case, the line

    services.AddSingleton(provider => Configuration);
    

    is equivalent to

    services.AddSingleton<IConfigurationRoot>(provider => Configuration);
    

    because the Configuration property on the class is declared as such, and injection will be done by matching whatever type it was registered as. We can replicate this pretty easily, which might make it clearer:

    public interface IParent { }
    
    public interface IChild : IParent { }
    
    public class ConfigurationTester : IChild { }
    
    public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddMvc();
    
        IChild example = new ConfigurationTester();
        services.AddSingleton(provider => example);
    }
    
    public class HomeController : Controller
    {
        public HomeController(IParent configuration)
        {
            // this will blow up
        }
    }
    

    However

    As stephen.vakil mentioned in the comments, it would be better to load your configuration file into a class, and then inject that class into controllers as needed. That would look something like this:

    services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
    

    You can grab these configurations with the IOptions interface:

    public HomeController(IOptions<AppSettings> appSettings)
    
    0 讨论(0)
  • 2020-12-14 02:32

    When moving a project from .Net Core 1.x to 2.0, change all IConfigurationRoot to IConfiguration

    0 讨论(0)
  • 2020-12-14 02:33

    In Core 2.0 it's recommended to use IConfiguration instead of IConfigurationRoot

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }
    
    public IConfiguration Configuration { get; }
    

    from https://docs.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/#add-configuration-providers

    0 讨论(0)
提交回复
热议问题