无法解析类型的服务

时间:2017-10-14 13:41:31

标签: c#

我有一个发送邮件异步函数的接口,我在我的控制器类中用于我的电子邮件功能。

IEmailSender emailSender

如您所见,我正在使用AccountController创建对象并将其设置为例程using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace solitude.admin.core.Interfaces { public interface IEmailSender { Task SendEmailAsync(string email, string subject, string message); } } 中的实例。

界面只由一个构造函数

组成
RCPP_MODULE

但问题是,当我来查看我的观点时,我收到以下错误:

  

InvalidOperationException:无法解析类型' solitude.admin.core.Interfaces.IEmailSender'尝试激活' solitude.admin.core.Controllers.AccountController'。
  Microsoft.Extensions.Internal.ActivatorUtilities.GetService(IServiceProvider sp,Type type,Type requiredBy,bool isDefaultParameterRequired)

2 个答案:

答案 0 :(得分:1)

You need to register how the DI engine will provide an IEmailSender. Assuming you are using asp.net core, you do this is in your Startup.cs in the ConfigureServices method:

public void ConfigureServices(IServiceCollection services) {
   ...
   services.AddSingleton<IEmailSender, EmailSenderImplementation>();
   ...
}

This is where EmailSenderImplementation is a class that implements the IEmailSender interface.

This registration tells the DI framework how to get an implementation of IEmailSender. In my example I am telling it to instantiate a single instance of EmailSenderImplementation and reuse that instance over the lifetime of the application. You might need to use AddTransient (if you want a new one every time you ask for one) or AddScoped (if you want a new one for each http request) instead of AddSingleton depending on how your implementation of IEmailSender works.

答案 1 :(得分:0)

Tim确实是正确的,我必须将以下代码添加到我的configure startup.cs

services.AddTransient<IEmailSender, AuthMessageSender>();

AuthMessageSender类由以下内容组成。

// This class is used by the application to send Email and SMS
// when you turn on two-factor authentication in ASP.NET Identity.
// For more details see this link http://go.microsoft.com/fwlink/?LinkID=532713
public class AuthMessageSender : IEmailSender 
{
   public Task SendEmailAsync(string email, string subject, string message)
   {
            // Plug in your email service here to send an email.
            return Task.FromResult(0);
    }         
}

这允许我正常地调用类中的函数我猜是旧的.net新如何处理这个可以有人向我解释为什么这个已经改变了核心为什么我们必须像这样硬线。