TempData依赖注入

时间:2014-06-06 03:47:10

标签: c# asp.net-mvc dependency-injection tempdata

我创建一个NotificationService来注入我的MVC控制器,这样我就可以在我的视图中显示toastr条消息。我最初将消息存储在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();
    }
}

1 个答案:

答案 0 :(得分:1)

对于基本要求,我会覆盖控制器中的OnActionExecuting ..然后将通知放在TempData中:

protected override void OnActionExecuting(ActionExecutingContext filterContext) {
    TempData["Notifications"] = _notificationService.GetNotifications(/* current user */);
    base.OnActionExecuting(filterContext);
}

在我们当前的项目中,我们使用通过专门用于此目的的动作呈现的PartialView。这对于复杂的设置来说更方便..但根据您的需要,这可能就足够了。