We have a third party control that is posting the same form parameters twice. We would like to patch the problem for now and notify them so we can continue using their controls. How do you modify a form parameter that is posted to an MVC controller's action method?
public ActionResult Index()
{
var httpParams = this.HttpContext.Request.Params;
if (httpParams["form_element"] != null ) {
httpParams["form_element"] = "some new value"; // NotSupportedException: Collection is read-only
}
return new CustomActionResult(this);
}
Trying to alter the request parameters does not work - it throws a NotSupportedException. Is there a way to redirect this request or do we need some custom HTTPHandler/Module to support this change? We want to control the request body values before the response is processed.
You cannot modify Request.Params and you should not also. As #Ben mentioned, it will be better if you use parameter or custom ModelBinder if you need to complex binding.
public ActionResult Index(string form_element)
{
if (form_element != null ) {
form_element = "some new value"; // not sure, why u need this. :)
}
return new CustomActionResult(this);
}
Or if you have some reason for not doing so, you can just write a wrapper class for the Params, put the logic inside that class. So, it will be easy to modify after the third party control is fixed.
public class ParamsWrapper
{
private NameValueCollection _collection = new NameValueCollection();
private static ParamsWrapper _instance;
public static ParamsWrapper Instance {
if(_instance == null) {
_instance = new ParamsWrapper(HttpContext.Current.Request.Params);
}
return _instance;
}
public ParamsWrapper(NameValueCollection collection) {
// added un-duplicated items to _collection from collection;
}
// put other methods that you want to interact
// for example,
public string this[string name] {
get {
return _collection[name];
}
}
}
In your action methods or other place,
public ActionResult Index()
{
var httpParams = ParamsWrapper.Instance;
return new CustomActionResult(this);
}
Hope it can help.
Thanks for your help, but I gave up on the issue - as it appears there is no possible way to achieve it. I decided to just fix the issue by removing the duplicate form elements before submitting the form using jQuery on the client.
Related
I have controllers which, for the sake of backwards compatibility, only have one action. The JSON request comes with an attribute "type" which determines what the action should do with it.
My idea for a clean solution was to build a set of action handlers. They all inherit from an abstract class called ActionHandler which has two methods
public abstract bool CanHandle(ClientRequest request);
and
public abstract object Handle(dynamic request)
And it has a property
public abstract string ActionForController { get; }
in which the specific actionhandlers just return the name of the controller they want to handle for. This is not very important, but may help clarify something later.
The controller is inserted with an ActionHandlerRegister which has an IEnumerable and a method "GetActionHandler". It returns the first specific ActionHandler that can handle the request.
public ActionHandler GetActionHandler(ClientRequest request)
{
foreach(var actionHandler in ActionHandlers)
{
if (actionHandler.CanHandle(request))
{
return actionHandler;
}
}
throw new BadRequestException(string.Format(CultureInfo.InvariantCulture, BadRequestExceptionTemplate, request.Type));
}
The controllers look like this:
public class LogController : ControllerBase
{
private readonly IActionHandlerRegister<LogController> logHandlers;
public LogController(IActionHandlerRegister<LogController> logHandlers)
{
this.logHandlers = logHandlers ?? throw new ArgumentNullException(nameof(logHandlers));
}
[HttpPost]
public async Task<IActionResult> Post([FromBody] dynamic rawJson)
{
var jsonBody = ((JsonElement)rawJson).ToString();
if (string.IsNullOrEmpty(jsonBody))
{
return BadRequest(ActionHandler.BadRequestRequestNullOrTypeMissingError);
}
var clientRequest = JsonSerializer.Deserialize<ClientRequest>(jsonBody);
if (clientRequest == null || string.IsNullOrEmpty(clientRequest.Type))
{
return BadRequest(ActionHandler.BadRequestRequestNullOrTypeMissingError);
}
try
{
var handler = logHandlers.GetActionHandler(clientRequest);
var result = handler.Handle(rawJson);
return Ok(result);
}
catch (BadRequestException ex)
{
return BadRequest(ex.Message);
}
}
}
For people paying attention: yes, I'm passing the rawjson to handler.Handle. This is because "ClientRequest" is something generic (from which I can read the type) but the handler needs the specific request, so it's deserializing again to something more specific. Maybe there are better solutions for that. Feel free to tell me.
In startup.cs, the insertion of the ActionHandlerRegister into the controller looks like this:
public void RegisterActionHandlersAsSingleton(IServiceCollection services)
{
IEnumerable<ActionHandler> listOfActionHandlers =
from domainAssembly in AppDomain.CurrentDomain.GetAssemblies()
from actionHandlerType in domainAssembly.GetTypes()
where actionHandlerType.IsAssignableFrom(typeof(ActionHandler))
select (ActionHandler)Activator.CreateInstance(actionHandlerType);
services.AddSingleton<IActionHandlerRegister<LogController>>(new ActionHandlerRegister<LogController>(listOfActionHandlers.Where(a => a.ActionForController == nameof(LogController))));
// other controllers ...
}
You might be able to guess, this last piece of code crashes at runtime telling me it's unable to cast to ActionHandler.
System.InvalidCastException: Unable to cast object of type
'System.Object' to type
'TcServerModules.ActionHandlers.ActionHandler'.
I have been playing around with different solutions, but none of them scratch that itch. What would be a nice, true-to OO-design principle
I have an extension for ActionResult that adds a toast to TempData when returning a page:
public static IActionResult WithMessage(this ActionResult result, InformMessage msg)
{
return new InformMessageResult(result, msg);
}
and this is InformMessageResult:
public class InformMessageResult : ActionResult
{
public ActionResult InnerResult { get; set; }
public InformMessage InformMessage { get; set; }
public InformMessageResult (ActionResult innerResult, InformMessage informMsg)
{
InnerResult = innerResult;
InformMessage = informMsg;
}
public override async Task ExecuteResultAsync(ActionContext context)
{
ITempDataDictionaryFactory factory = context.HttpContext.RequestServices.GetService(typeof(ITempDataDictionaryFactory)) as ITempDataDictionaryFactory;
ITempDataDictionary tempData = factory.GetTempData(context.HttpContext);
tempData.Put("InformMessage", InformMessage);
await InnerResult.ExecuteResultAsync(context);
}
}
This works well with
return RedirectToPage(etc).WithMessage(etc)
and the like, but fails with
return Page().WithMessage(etc)
and the debugger highlights
await InnerResult.ExecuteResultAsync(context);
saying InnerResult not set to an instance of an object.
Is there a way I can make this work with Return Page()?
Edit for additional info:
I tested what was being sent in as the "InnerResult" and it looks like with Return Page(), everything is null (by design, I'd say, as I do nothing to it before that point):
with RedirectToPage():
With Page():
This is an older question, but I needed functionality like this myself, and dug deep to find the reason.
As you can see from your debugging, the Page method generates a completely blank PageResult. Being as every property is null, calling ExecuteResultAsync on it fails as it obviously can't do anything with all-null values.
The reason Page() otherwise works the rest of the time is due to behind-the-scenes magic in PageActionInvoker, specifically in its InvokeResultAsync method. It will detect that your ViewData and Page are blank and populate them before it, itself, calls the pageResult.ExecuteResultAsync method.
Hence, you can still get your InformMessageResult to work if you do the same work as PageActionInvoker does. Here's how:
public override async Task ExecuteResultAsync(ActionContext context)
{
/* temp data work goes here */
if (InnerResult is PageResult pageResult)
{
var pageContext = context as PageContext
?? throw new ArgumentException("context must be a PageContext if your InnerResult is a PageResult.", "context");
var pageFactoryProvider = pageContext.HttpContext.RequestServices.GetRequiredService<IPageFactoryProvider>();
var pageFactory = pageFactoryProvider.CreatePageFactory(pageContext.ActionDescriptor);
var viewContext = new ViewContext(
pageContext,
NullView.Instance,
pageContext.ViewData,
tempData,
TextWriter.Null,
new Microsoft.AspNetCore.Mvc.ViewFeatures.HtmlHelperOptions()
);
viewContext.ExecutingFilePath = pageContext.ActionDescriptor.RelativePath;
pageResult.ViewData = viewContext.ViewData;
pageResult.Page = (PageBase)pageFactory(pageContext, viewContext);
}
await InnerResult.ExecuteResultAsync(context);
}
private class NullView : IView
{
public static readonly NullView Instance = new NullView();
public string Path => string.Empty;
public Task RenderAsync(ViewContext context)
{
if (context == null) throw new ArgumentNullException("context");
return Task.CompletedTask;
}
}
The problem I suspect is that Page() and RedirectToPage() inherit from different base classes.
RedirectToPage() as per this documentation. It has the following Inheritance:
Object -> ActionResult -> RedirectToPageResult
This is exposed by some inheritance of the controller. So you're extension of ActionResult is available to be used.
However the Page() method is part of a RazorPages class as per this documentation. So it's inheritance is as follows:1
Object -> RazorPageBase -> PageBase -> Page
Now the Page() method of that class does return a PageResult which looks to inherit from ActionResult as defined here.
So with that in mind I'd suggest casting it to the base ActionResult first, and then using your extension method. Something like this perhaps:
var baseClass = (Page() as ActionResult);
return baseClass.WithMessage(etc);
1 You can see the base type in the second image the OP supplied.
Page() and RedirectToPage() are helper methods for PageResult and RedirectToPageResult respectively. So instead of newing up you call these methods.
When you call Page() it calls ExecuteResultAsync behind the scenes to render the PageResult. At that point, all the properties are null i.e. Page, Model, ViewData etc. As the result is already rendered, So you can't call another ExecuteResultAsync using the WithMessage extension method.
When you call RedirectToPage it issues a 301/302 and generates a new Request that will result in RedirectToPageResult. So the RedirectToPageResult is not rendered yet and you have the option to utilise your WithMessage extension method.
Having said that, I don't think it's possible to utilise the WithMessage when using Page() method, AFAIK.
I'm trying to create better separation of concerns for code reuse in my program, that way I don't have a bloated controller that does all these different things.
for instance, in my application I have a user profile where users can upload a profile pic. If they don't customize their profile pic, I set the default profile pic to an avatar. I do this through a method to check if their profile pic string is null.
I created a folder called HelperMethods and created a class called UserHelperMethods which currently has one function:
namespace HiRatik.Stories.HelperMethods
{
public class UserHelperMethods
{
//checks if the user's profile pic is null and sets it to default pic if it is
public string GetUserProfilePic(ApplicationUser user)
{
if (user.ProfilePic == null)
{
user.ProfilePic = "profile_pic_default.png";
}
return user.ProfilePic;
}
}
}
Now, in the controller, under the controller's folder, I added using HiRatik.Stories.HelperMethods;
and tried to call the public function GetUserProfilePic from the UserController. But I'm getting an error on the implementation. I'd like to be able to place a lot of these general functions related to users in another class like UserHelperMethods to clean up the bulk in the controller, but I'm missing something on the implementation. the using statement at the top is grayed out, so it's not picking up the function call. Any ideas?
You need to add an instance of the helper method class to every class you want to use it in.
UserHelpMethods helper = new UserHelperMethods();
then you can use it as:
helper.GetUserProfilePic(foundUser);
...
help.DoSomethingImportant(foundUser);
You may want to make this into an Extension. Then you will be able to call it like this:
user.GetProfilePic();
The changes you have to do is, to make both your class and method static and have the this keyword before the parameter. Something like
public static class ApplicationUserExtensions
{
//checks if the user's profile pic is null and sets it to default pic if it is
public static string GetProfilePic(this ApplicationUser user)
{
if (user.ProfilePic == null)
{
user.ProfilePic = "profile_pic_default.png";
}
return user.ProfilePic;
}
}
I would consider making these methods static.
namespace HiRatik.Stories.HelperMethods
{
public class UserHelperMethods
{
//checks if the user's profile pic is null and sets it to default pic if it is
public static string GetUserProfilePic(ApplicationUser user)
{
if (user.ProfilePic == null)
{
user.ProfilePic = "profile_pic_default.png";
}
return user.ProfilePic;
}
}
}
If the helper methods don't rely on any state within the UserHelperMethods object, this will make it much easier to call your methods from anywhere, as there is no longer a need to create an instance of the UserHelperMethods type. You can call the method like this.
UserHelperMethods.GetUserProfilePic(foundUser);
just create instance of the class
var myInstance = new UserHelperMethods();
then just use myInstance object to access the functions in UserHelpMethods class
so you can call any function in UserHelpMethods like this
myInstance.FunctionName();
so in your case it will be like
myInstance.GetUserProfilePic(foundUser);
you could update your code to one of the following
A -
namespace HiRatik.Stories.HelperMethods
{
public class UserHelperMethods
{
private static UserHelperMethods _instance = null;
public static UserHelperMethods Instance()
{
if(_instance == null)
{
_instance = new UserHelperMethods();
}
return _instance;
}
//checks if the user's profile pic is null and sets it to default pic if it is
public string GetUserProfilePic(ApplicationUser user)
{
if (user.ProfilePic == null)
{
user.ProfilePic = "profile_pic_default.png";
}
return user.ProfilePic;
}
}
}
and inside your Controller just use call it like this
UserHelperMethods.Instance().GetUserProfilePic(founduser);
Or the easiest way
var helperObj = new UserHelperMethods();
helperObj.GetUserProfilePic(founduser);
the diff you won't need to create instance all the time in diff controllers
I wish this help you !!
I have an MVC 5 website that uses Entity Framework for the database interactions.
I would like to use an IEnumerable as a private variable in a controller so that other custom ActionResults in the same controller can use the same information without having to re-query each time. I don't mean the other CRUD ActionResults, but rather other custom methods that do things with the data seen on the Index page, which is usually a subset of the full database table. It would be helpful to query once, then re-use the same data.
In this example, I have private IEnumerable<CourseList> _data; as a class-level variable and IEnumerable<CourseList> data as an Index()-level variable. I use Debug.WriteLine to determine if each variable is empty or not.
As I expect, within the scope of the Index() ActionResult both variables data and _data are not null. Within the scope of ClickedFromIndexPageLink(), _data -- the class-level variable is null.
My theory is that while i have sequentially loaded Index first, the controller doesn't know that. And as far as the controller is concerned, when I request _data contents in the other ActionResult, it hasn't been filled yet. However, in real time, I have clicked Index first and so should expect to see _data filled with the Index query.
To see what I do as a workaround, scroll down to see "Method B (does work, but is repetitive)".
Ts there any simple way to have an IEnumerable used as a private class variable in this manner, or is my workaround the only possible approach?
Method A (doesn't work):
Debug.WriteLine() results:
Begin Index() test *****
Is data Null? Not Null
Is _data Null? Not Null
End Index test *****
Begin ClickedFromIndexPageLink() test*****
Is _data Null? Null
End ClickedFromIndexPageLink test*****
The code:
using IenumerableAsClassVariable.Models;
using System.Collections.Generic;
using System.Data.Entity;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Web.Mvc;
namespace IenumerableAsClassVariable.Controllers
{
// This is the helper class & function used to determine if the IEnumerable is null or empty
public static class CustomHelpers
{
public static string IsNullOrEmpty<T>(this IEnumerable<T> enumerable)
{
if (enumerable == null)
return "Null";
else
return "Not Null";
}
}
public class CourseListsController : Controller
{
private CreditSlipLogContext db = new CreditSlipLogContext();
private IEnumerable<CourseList> _data;
// If IEnumerable is null or empty return true; else false.
// GET: CourseLists
public ActionResult Index()
{
IEnumerable<CourseList> data = db.CourseLists.AsEnumerable();
Debug.WriteLine("-----");
Debug.WriteLine("Begin Index test *****");
Debug.WriteLine("Is data Null? " + CustomHelpers.IsNullOrEmpty(data));
_data = data;
Debug.WriteLine("Is _data Null? " + CustomHelpers.IsNullOrEmpty(_data));
Debug.WriteLine("End Index test *****");
return View(db.CourseLists.ToList());
}
public ActionResult ClickedFromIndexPageLink()
{
Debug.WriteLine("Begin ClickedFromIndexPageLink test*****");
Debug.WriteLine("Is _data Null? " + CustomHelpers.IsNullOrEmpty(_data));
Debug.WriteLine("End ClickedFromIndexPageLink test*****");
ViewBag.IsDataNull = CustomHelpers.IsNullOrEmpty(_data);
return View();
}
#region OtherCrudActionResultsAreHidden
#endregion
}
}
Method B (does work, but is repetitive):
As I expect, my results aren't null:
Begin ClickedFromIndexPageLink test*****
Is data Null? Not Null
Is _data Null? Not Null
End ClickedFromIndexPageLink test*****
This is because I re-query in the ActionResult, just as I do in the Index() ACtionResult:
public ActionResult ClickedFromIndexPageLink()
{
IEnumerable<CourseList> data = db.CourseLists.AsEnumerable();
Debug.WriteLine("Begin ClickedFromIndexPageLink test*****");
Debug.WriteLine("Is data Null? " + CustomHelpers.IsNullOrEmpty(data));
_data = data;
Debug.WriteLine("Is _data Null? " + CustomHelpers.IsNullOrEmpty(_data));
Debug.WriteLine("End ClickedFromIndexPageLink test*****");
ViewBag.IsDataNull = CustomHelpers.IsNullOrEmpty(_data);
return View();
}
Everytime you call an action method is a separate Http request. Remember, Http is stateless and one request has no idea what the previous request did. so you won't get the private variable value you did set in your previous action method call.
You may consider caching the data which will be available to multiple requests until the cache expires. You may use the MemoryCache class available in dot net.
Quick sample
const string CacheKey = "courses";
public ActionResult Index()
{
var courseList = GetCourses();
// do something with courseList
return View(courseList );
}
public ActionResult List()
{
var course = GetCourses();
// do something with courseList
return View(course);
}
private List<Category> GetCourses()
{
var db = new YourDbContext();
var cache = MemoryCache.Default;
if (!cache.Contains(CacheKey)) // checks to see it exists in cache
{
var policy = new CacheItemPolicy();
policy.AbsoluteExpiration = DateTime.Now.AddDays(1);
var courses = db.CourseLists.ToList();
cache.Set(CacheKey , courses, policy);
}
return (List<Category>) cache.Get(CacheKey);
}
Of course you may move this away from your controller code to a new class/layer to keep separation of concern.
If you prefer to convert your entity object to simply POCO/ViewModel collection before storing in cache,
var courseVms = db.CourseLists.Select(s=>new CourseViewModel {
Id =s.Id, Name=s.Name }).ToList();
cache.Set(cacheKey, courseVms , policy);
And your GetCourses method will be returning a List<CourseViewModel>
Remember, caching will keep the data until the cache expires. So it is a good idea to keep data which won't usually change that often (Ex: Look up data etc). If you are caching your transactional data, you need to update the cache every time a change is made to the data (Ex : A new course is added, one course is deleted etc..)
MemoryCache class resides in System.Runtime.Caching namespace which resides in System.Runtime.Caching.dll. So you need to add a reference to this assembly.
If you want to do the same kind of caching within your ASP.NET5/ MVC6 application, You may use the IMemoryCache implementation as explained in this answer.
Shyju's answer is right in that you need caching but I'd recommend the following options over managing a MemoryCache:
1) Use the ASP.NET cache in System.Web.Caching. Add to cache via Cache.Add, retrieve using the indexer (Cache["key"]) or Get. Note that this is a static reference so if you need to get at this in a business logic library you'll need to set up your data as a dependency of your business objects (you probably are going to want to inject this IEnumerable into the constructor of your controller at the very least).
2) Use a singleton. If you're not going to change this data, you can simply create a static IList or IReadOnlyList and set it once at application start (making it static, not an instance property is the key to making this persist across requests). You can wrap it via the more traditional singleton pattern if you want. You could also use an IoC container and register it as a singleton with an initializer method and let the container inject it where it is needed. *Note that a static property like this is inherently not thread-safe. If you need to change this data, use one of the thread-safe (concurrent) collections.
To sum up, here is the sequence of events you want:
(Design time)
-define static thing
(Application start)
-Set static thing to data/initialize static thing
(Application runtime)
-Access static thing
#Shyju answered my question:
Everytime you call an action method is a separate Http request. Remember, Http is stateless and one request has no idea what the previous request did. so you won't get the private variable value you did set in your previous action method call.
I have not yet delved into caching, but part of his answer inspired me to adjust my code, so that I write my index query only once, but can call it from whatever method in the same controller that I want. In the end, it's still using Method B (presented in my question), but it enables me to type my index query only once and reduce typo or other simple coding errors that come from reduplicating code.
using IenumerableAsClassVariable.Models;
using System.Collections.Generic;
using System.Data.Entity;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Web.Mvc;
using System.Web.Caching;
namespace IenumerableAsClassVariable.Controllers
{
// This is the helper class & function used to determine if the IEnumerable is null or empty
public static class CustomHelpers
{
public static string IsNullOrEmpty<T>(this IEnumerable<T> enumerable)
{
if (enumerable == null)
return "Null";
else
return "Not Null";
}
}
public class CourseListsController : Controller
{
private CreditSlipLogContext db = new CreditSlipLogContext();
// This this the "index" query that is called by the Index
// and can be called by any other methods in this controller that I choose.
private IEnumerable<CourseList> GetIndexQuery()
{
using (var dbc = new CreditSlipLogContext())
{
return db.CourseLists.AsEnumerable();
}
}
// GET: CourseLists
public ActionResult Index()
{
var data = GetIndexQuery();
Debug.WriteLine("-----");
Debug.WriteLine("Begin Index test *****");
Debug.WriteLine("Is data Null? " + CustomHelpers.IsNullOrEmpty(data));
Debug.WriteLine("End Index test *****");
return View(db.CourseLists.ToList());
}
public ActionResult ClickedFromIndexPageLink()
{
var data = GetIndexQuery();
Debug.WriteLine("-----");
Debug.WriteLine("Begin Index test *****");
Debug.WriteLine("Is data Null? " + CustomHelpers.IsNullOrEmpty(data));
Debug.WriteLine("End Index test *****");
ViewBag.IsDataNull = CustomHelpers.IsNullOrEmpty(data);
return View();
}
#region OtherCrudActionResultsAreHidden
#endregion
}
}
I'm writing a project in c# asp.net mvc3, and I have a helper-class that looks like this:
using System.Collections.Generic;
using System.Web;
namespace CoPrice.Helpers
{
public static class Messages
{
public static IList<Message> All
{
get
{
var list = ((IList<Message>)HttpContext.Current.Session["_messages"]) ?? new List<Message>();
HttpContext.Current.Session["_messages"] = new List<Message>();
return list;
}
}
public static bool Exists
{
get
{
return (((IList<Message>)HttpContext.Current.Session["_messages"]) ?? new List<Message>()).Count > 0;
}
}
public static void Add(MessageType type, string message)
{
Message m = new Message
{
Type = type,
Text = message
};
HttpContext.Current.Session["_messages"] = HttpContext.Current.Session["_messages"] as List<Message> ?? new List<Message>();
((IList<Message>)HttpContext.Current.Session["_messages"]).Add(m);
}
public enum MessageType
{
Info,
Success,
Error
}
public struct Message
{
public MessageType Type;
public string Text;
}
}
}
However, when I try to use these in a test, it crashes (cause of HttpContext.Current beeing null). How can I make this work both in tests and in the app itself? I don't mind having to change this class to use something else than HttpContext.Current to access the session, but I want it to have properties as it does, so it can't take the session-object as a parameter.
Any ideas on how to solve this problem?
You need to define an IMessagesProvider and use an DI container to inject the implementation of the IMessagesProvider. In real use you'll have an implementation that uses the ASP.Net session. In test use you'll mostly mock it. BTW, you probably shouldn't have a static Messages class. In fact, IMessagesProvider will probably replace your static Messages class.
Ex:
public class FooController : Controller
{
IMessagesProvider _messages;
public FooController(IMessagesProvider messages)
{
// Your DI container will inject the messages provider automatically.
_messages = messages;
}
public ActionResult Index()
{
ViewData["messages"] = _messages.GetMessages(Session.SessionId);
return View();
}
}
Mind you, this is a very simple example. In fact, you probably want one more class which is the model that drives the view. A quick intro:
public ActionResult Index()
{
var model = PrepareModel(_messages);
return View(model);
}
"PrepareModel" is your very own method that instantiates a new model class, fills it with the necessary data, and then you send it off to your view. It's typical to have one model class per view defined. E.g. you'd have model classes like "SignupFormModel", "DashboardModel", "ChatModel", etc., Doing so allows you to have strongly-typed views as well (a great thing).
You can also implement a mock session object that inherits from HttpSessionStateBase class
#xanadont is right that you need to turn Messages into a normal class. But (and I know this is heresy in some circles) there's no need for a one-off interface and a full-blown DI framework. Just make the methods on your Messages class virtual so you can mock them in your unit-tests, and use constructor injection:
public class FooController : Controller
{
Messages _messages;
// MVC will call this ctor
public FooController() : this(new Messages())
{
}
// call this ctor in your unit-tests with a mock object, testing subclass, etc.
public FooController(Messages messages)
{
_messages = messages;
}
}