I'm currently refactoring a bloated MVC .NET Core app to a more simpler .NET Core app using Razor Pages and Mediatr.
In the MVC approach there's a BaseController that all controllers inherits from. The BaseController handles the Mediatr DI. How will I go about doing this in Razor Pages? Is it wise to create a BasePageModel class that handles the Mediatr DI, or should I just include the Mediatr DI in every PageModel I create?
I'm using a BasePageModel class to hold common code and properties. The subclasses get the DI injected objects and then pass them up to the base class which handles them with an optional parameters list. There might be more elegant way to accomplish this but this is working well for me.
public class BasePageModel : PageModel {
public BasePageModel(params object[] list) {
foreach (var item in list) {
if (item is ILoggerFactory loggerFactory) {
_logger = loggerFactory.CreateLogger("Projects");
}
if (item is ApplicationDbContext context) {
_dbContext = context;
}
if (item is UserManager<ApplicationUser> manager) {
_userManager = manager;
}
if (item is IHostingEnvironment env) {
_environment = env;
}
}
}
public class IndexModel : BasePageModel {
public IndexModel(ApplicationDbContext context, UserManager<ApplicationUser> userManager, ILoggerFactory loggerFactory) :
base(context, userManager, loggerFactory) { }
}