ASP.Net Core MVC Dependency Injection not working

前端 未结 3 511
时光说笑
时光说笑 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(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(Configuration.GetSection("AppSettings"));
    

    You can grab these configurations with the IOptions interface:

    public HomeController(IOptions appSettings)
    

提交回复
热议问题