尝试在同样使用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中注册正确的Postal类型。 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...
}
答案 0 :(得分:0)
我认为你的怀疑是正确的。应用程序初始化期间HttpContext
不可用。因此,在ControllerContext
活动中,邮政将无效(因为它依赖于ViewContext
和Application_Start
)。
由于您正在使用DI,因此这也扩展到使用Unity配置的每个类的构造函数 - 您不能在构造函数中使用Postal,但可以在Application_Start
之后调用的方法中完成。
您需要将调用移至Application_Start
之外的Postal,或者在这种情况下使用本机.NET邮件库(因为它们依赖于System.Net且不依赖于HttpContext
)
答案 1 :(得分:0)
很抱歉回答我自己的问题,但我终于能够解决这个问题了。
从方法中删除async
后,一切都按预期开始工作。
所以改变......
public async Task<ActionResult> SendEmail(EmailViewModel viewModel)
对此...
public ActionResult SendEmail(EmailViewModel viewModel)
然后我就可以发送电子邮件而不会在Unity.Mvc4.UnityDependencyResolver.get_ChildContainer()
内触发异常。
我不确定为什么我无法在.Send()
方法中拨打邮政async
(旁注,我试着致电{{1}导致相同的Unity问题)。如果有人能够了解为什么这会在.SendAsync()
方法中发挥作用,那将非常感激。
感谢。