我正在创建一个NotificationService以插入到我的MVC控制器中,以便在我的视图中显示烤面包消息。我最初打算将消息存储在HttpContext.Current.Items中,但有时控制器重定向到成功的另一个视图。
我认为TempData可能是第二好的。但是,我不确定如何使用依赖注入将TempData注入到NotificationService中?
用代码示例更新:
public enum NotifyType
{
Success,
Error,
Warn,
Info
}
public class NotificationMessage
{
public NotificationMessage(NotifyType notifyType, string message)
{
NotifyType = notifyType;
Message = message;
}
public NotifyType NotifyType { get; set; }
public string Message { get; set; }
}
public interface INotificationService
{
void Success(string message);
void Error(string message);
void Warn(string message);
void Info(string message);
List<NotificationMessage> GetMessages();
}
public class HttpNotificationService : INotificationService
{
private TempDataDictionary _tempData;
public HttpNotificationService(TempDataDictionary tempData)
{
_tempData = tempData;
}
private void SetNotification(NotificationMessage notificationMessage)
{
List<NotificationMessage> messages = GetMessages();
messages.Add(notificationMessage);
_tempData["Notifications"] = messages;
}
public void Success(string message)
{
SetNotification(new NotificationMessage(NotifyType.Success, message));
}
public void Error(string message)
{
SetNotification(new NotificationMessage(NotifyType.Error, message));
}
public void Warn(string message)
{
SetNotification(new NotificationMessage(NotifyType.Warn, message));
}
public void Info(string message)
{
SetNotification(new NotificationMessage(NotifyType.Info, message));
}
public List<NotificationMessage> GetMessages()
{
return _tempData["Notifications"] as List<NotificationMessage> ?? new List<NotificationMessage>();
}
}
public class HomeController : Controller
{
private INotificationService _notificationService;
public HomeController(INotificationService notificationService)
{
_notificationService = notificationService;
}
public ActionResult Action()
{
// Do something
_notificationService.Success("Hooray, you succeeded!");
return View();
}
}发布于 2014-06-06 03:54:52
对于基本需求,我将覆盖控制器中的OnActionExecuting。然后将通知放在TempData中:
protected override void OnActionExecuting(ActionExecutingContext filterContext) {
TempData["Notifications"] = _notificationService.GetNotifications(/* current user */);
base.OnActionExecuting(filterContext);
}在我们的当前项目中,我们使用一个PartialView,它是通过一个特定于此目的的操作呈现的。这对复杂的设置来说更方便。但这可能就足够了,这取决于你的需求。
https://stackoverflow.com/questions/24073855
复制相似问题