I have an app that is written using c# and ASP.NET MVC 5. I'm also using Unity.Mvc for dependency injection.
Along with many other classes, the class MessageManager
is registered in the IoC
container. However, the MessageManager
class depends on an instance of TempDataDictionary
to perform its work. This class is used to write temporary data for the views.
In order to resolve an instance of MessageManager
I need to also register an instance of TempDataDictionary
. I would need to be able to add values to TempDataDictionary
from the MessageManager
class and then I would need to access the temp data from the view. Therefore, I need to be able to access the same instance of TempDataDictionary
in the views so I can write out the messages to the user.
Also, if the controller redirects the user elsewhere, I don't want to lose the message, I still want to be able to show the message on the next view.
I tried the following to register both TempDataDictionary
and MessageManager
:
Container.RegisterType<TempDataDictionary>(new PerThreadLifetimeManager())
.RegisterType<IMessageManager, MessageManager>();
Then in my view, I have the following to resolve to an instance of IMessageManager
var manager = DependencyResolver.Current.GetService<IMessageManager>();
However, the message gets lost for some reason. That is, when I resolve manager
, TempDataDictionary
doesn't contain any messages that were added by MessageManager
from the controller.
How can I correctly register an instance of the TempDataDictionary
so the data persists until it is viewed?
UPDATED
Here is my IMessageManager
interface
public interface IMessageManager
{
void AddSuccess(string message, int? dismissAfter = null);
void AddError(string message, int? dismissAfter = null);
void AddInfo(string message, int? dismissAfter = null);
void AddWarning(string message, int? dismissAfter = null);
Dictionary<string, IEnumerable<FlashMessage>> GetAlerts();
}
MessageManager
implementation as well. You appear to have a misunderstanding about howTempDataDictionary
is used within the framework. Its sole purpose is to pass data between the current and next HTTP requests Check out this article to get a better understanding When to use ViewBag, ViewData, or TempData in ASP.NET MVC 3 applications – Annulation