【发布时间】:2018-10-21 22:32:15
【问题描述】:
我想在我的项目中进行电子邮件激活。我使用实体框架与存储库层中的数据库连接,而服务使用这些层。
我想在没有非控制器的情况下使用实体框架和依赖注入服务创建密钥并插入数据库。
存储库层
public void Insert(T entity)
{
if (entity == null)
{
throw new ArgumentNullException("entity");
}
_entities.Add(entity);
SaveChanges();
}
激活服务
public void Insert(EmailValid entity)
{
_repositoryBase.Insert(entity);
}
非控制器类
public class EmailActivaitonKey
{
private readonly IActivationService _activationService;
public EmailActivaitonKey()
{
this._activationService = Startup.ActivationService;
}
public string ActivationKey(string email)
{
string guid = Guid.NewGuid().ToString();
while (_activationService.GetByFilter(i => i.ActivationKey == guid) != null)
{
guid = Guid.NewGuid().ToString();
}
string key = email + ":OSK:" + DateTime.Now + ":OSK:" + guid;
EmailValid emailValid = new EmailValid
{
Email = email,
Time = DateTime.Today,
ActivationKey = key
};
_activationService.Insert(emailValid);
return new Helpers.AESEncryption().EncryptText(key);
}
}
在其他类中声明 EmailActivationKey
MailMessage mailMessage = new MailMessage
{
From = new MailAddress("***@***.***"),
Body = "Crypto Box Activation",
Subject = $"<a href='/Email/Activation?key={new EmailActivaitonKey().ActivationKey(email)}'><h1>Click For Activation<h1><a>",
To = { email }
};
在启动中:
public static IActivationService ActivationService;
//then
services.AddScoped<IActivationService, ActivationService>();
ActivationService = services.BuildServiceProvider().GetService<IActivationService>();
我查看了this question 和this one too,但没有得到任何结果。
【问题讨论】:
-
如果你没有控制器,你希望这段代码如何运行?
-
为什么人们认为依赖注入只适用于控制器,这是一个错误的假设。
-
我知道依赖注入,但我无法调用函数,原因是类的构造函数有一个参数@JoeAudette
-
构造函数是依赖注入的方式,它需要的任何参数也必须向DI注册
标签: c# asp.net-core dependency-injection