尝试在也使用 Mvc.Unity4 的 MVC 应用程序中使用 Postal 时,我遇到了一个奇怪的问题。
我相信这个问题是由于无法访问HttpContext
.
我尝试使用 Postal 从我的一个控制器内部发送电子邮件:
dynamic e = new Email("AccountActivation");
e.To = "name@email.com"
e.Send();
尝试发送电子邮件会导致以下异常Unity.Mvc4.UnityDependencyResolver
:
[NullReferenceException: Object reference not set to an instance of an object.]
Unity.Mvc4.UnityDependencyResolver.get_ChildContainer() +57
Unity.Mvc4.UnityDependencyResolver.GetService(Type serviceType) +241
System.Web.Mvc.DefaultViewPageActivator.Create(ControllerContext controllerContext, Type type) +87
System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +216
Postal.EmailViewRenderer.RenderView(IView view, ViewDataDictionary viewData, ControllerContext controllerContext, ImageEmbedder imageEmbedder) +182
Postal.EmailViewRenderer.Render(Email email, String viewName) +204
Postal.EmailService.CreateMailMessage(Email email) +72
Postal.EmailService.Send(Email email) +65
我对 Mvc.Unity4 不太熟悉,因为它是由不同的开发人员添加的。
抓住最后一根稻草,我确实尝试在 Application_Start 中注册正确的邮政类型。Unity 容器的初始化发生在Bootstrapper.cs
:
container.RegisterType<UsersController>(new InjectionConstructor());
container.RegisterInstance<IEmailService>(new EmailService());
在我的控制器中,我有:
private IEmailService _emailService;
public UsersController()
{
_emailService = new Postal.EmailService();
}
public UsersController(Postal.EmailService emailService)
{
_emailService = emailService;
}
[HttpPost]
public async Task<ActionResult> SendEmail(EmailViewModel viewModel)
{
dynamic e = new Email("AccountActivation");
e.ViewData.Add("To", "name@email.com");
e.ViewData.Add("From", "no-reply@email.com");
_emailService.Send(e);
More code...
}