Right way to derive controllers from a base controller - asp.net-mvc

I tend to consume the same set of repositories from all my controllers. That is, I instantiate repository objects (with IoC) in every controller.
I think I could derive my controllers from a base controller that could instantiate these objects in one place. Could you point me to the right of doing this? Thank you for your help.

You have a number of options, and which one is "the right way" is really up to you and how your system functions overall. There could be performance issues for various instantiated objects that need to be considered, etc.
One option could be as simple as:
public class BaseController
{
protected ISomeRepository myRepository = IoCContainer.Resolve<ISomeRepository>();
}
public class MyController : BaseController { }
Additionally, you could move the initialization to the base controller's constructor rather than have it be inline like that.
Another option might be to late-bind the repositories, if having them all incurs a performance hit (weighed carefully with the hit of instantiating them) and on average they aren't always needed:
public class BaseController
{
private ISomeRepository _myRepository;
protected ISomeRepository myRepository
{
get
{
if (_myRepository == null)
_myRepository = IoCContainer.Resolve<ISomeRepository>();
return _myRepository;
}
}
}
There are probably more options available to you, it all depends on your setup. How your particular IoC container works may also play heavily into your design decision.
(Note that I reference the IoCContainer directly here for brevity and simplicity, but I recommend abstracting out the container behind a service locator so that you don't have so many references to the container itself.)

Actually, it depends on what kind of tasks should those "Common Repositories" complete. If they are directly relate to what Action supposed to do - maybe that is okay. But you'll anyway face some problems with IoC-resolution. In order to avoid injecting those repositories all the time for each new Repo you'll have to make a dependency on Service Locator in your base controller. Which isn't good thing.
If those Repositories are ther efor something that is orthogonal to what Action is going to do - then it is more like AOP-kinda logic, so I'd better use Action Filters for that or RenderAction.
In common case, I'd try to avoid layer supertype dependencies as well as would prefer Composition over Inheritance.

Related

Common functionality across multiple ASP.NET MVC controllers

I'm working on ASP.NET MVC application & have a quick design question for you.
So I need to implement a common functionality for all my controllers (well, most of them).
I don't want to repeat the same logic in all the controllers.
What'd be the ideal approach in the best interest of MVC?
I found people saying create base controller and inherit it in your controllers. But when I visualize a controller, I can see it'd contain only action methods that return some content/views - Correct me if I'm wrong.
OneController
{
ActionMethod A1
{
//Code to return list of objects for the given integer value. So it calls database stored procedure.
}
}
...multiple such controllers are there.
I'd still like to have A1 exists in the OneController, just put its logic somewhere common place.
Also some people suggest to create just plain Helper class to place the common method.
Could you please suggest me what approach will be better (Or any other appropriate approach)? Thanks.
I agree with you that, most of the times, it only makes sense to inherit from base controllers when we're talking about Actions or methods that are really related. But of course, you can just use base controllers for everything. Your choice.
Other than that, you have 2 options. For classes that have little to no chance of being polymorphic (change behavior depending on the implementation), you are fine to create static classes and just use them inside your controllers. An example would be a class that does math calculations, these are not that polymorphic by nature.
For all the other cases, I'd strongly suggest that you use dependency injection. One of the reasons being that unit testing will become way easier. Here's a guide on how to do it for MVC 4 onwards using the built in engine: https://www.asp.net/mvc/overview/older-versions/hands-on-labs/aspnet-mvc-4-dependency-injection. If you don't want to use it and use Ninject or Simple Injector, you can implement your own ControllerActivator and use Ninject, for instance, to get an instance of your controller.
When using dependency injector, normally your controller would get the dependencies in the constructor, like this:
public class StoreController : Controller
{
private IStoreService service;
public StoreController(IStoreService service)
{
// service in an injected dependency
this.service = service;
}
}
For more information, Google ASP.NET dependency injection.

ASP.NET 5 / Core 1 Dependency Injection: Bad design or bad documentation?

I'm reading through the ASP.NET 5 docs and was choking on the chapter of dependency injection.
I am recommended to write my controllers like so:
public class MyController: Controller
{
private readonly MyService _myService;
public MyController(MyService myService)
{
_myService = myService;
}
public IActionResult Index()
{
// use _myService
}
}
The short and direct version is discouraged:
public class MyController : Controller
{
public IActionResult Index()
{
var myService = (MyService)HttpContext.RequestServices.GetService(typeof(MyService));
}
}
The given reason is because allegedly the recommended version...
[...] yields classes that are easier to test (see Testing) and are more loosely coupled.
The linked testing chapter doesn't shed any light on this weird statement.
I didn't look at the sources, but I assume whatever constructs the controller is using HttpContext.RequestServices.GetService itself to deliver the dependency? Clearly a test can setup a different implementation for testing, and clearly that is the whole point of a DI framework, right?
The colossus (MyService)HttpContext.RequestServices.GetService(typeof(MyService)) is bad enough, but a small helper could fix that (was a simple Get<MyService>() really so hard?).
But that this excessive clutter is recommended for basically every controller and more is disturbing.
It's all the more puzzling as there already is a Microsoft DI framework with a proper usage, MEF:
public class MyController : Controller
{
[Import]
private MyService _myService;
public IActionResult Index()
{
// use _myService
}
}
Why not at least just take that one? What's going on here?
This isn't a ASP.NET Core specific solution. This is how just about every DI framework works. The most common approach is to have all the dependencies of a controller as constructor parameters. This makes it clear what services the controller uses. There are multiple alternative solutions, but the basic idea stays the same and there are multiple pros and cons to them.
Clearly a test can setup a different implementation for testing, and clearly that is the whole point of a DI framework, right?
This line isn't clear to me. What do you think the 'whole point of a DI framework ' is? This line suggest you only use it so you can use a different implementation for testing.
But that this excessive clutter is recommended for basically every controller and more is disturbing.
Excessive clutter? What if I want to use MyService in two (or more) functions? Should I use this:
public class MyController : Controller
{
public IActionResult Index()
{
var myService = (MyService)HttpContext.RequestServices.GetService(typeof(MyService));
}
public IActionResult Index2()
{
var myService = (MyService)HttpContext.RequestServices.GetService(typeof(MyService));
}
}
Or should I opt for the solution where I set it up in the constructor? Seems like an obvious choice to me. In such a small example it may look like clutter, but add 10 lines of code to it and you'll barely notice a small constructor and some variable declarations.
You can use it while testing. It's a way to quickly grab something from the container when you need it, but it should certainly not be part of the actual code. You're simply hiding the dependency from sight.
At last you suggest property injection. This is a valid solution. But an often used argument against it is that it hides the dependency. If you define it as a parameter in the constructor you can't hide it. Besides, a lot of DI frameworks don't even have support for property or method injection because of this.
If you want to use MEF in your project you are free to do so. But it should, in my opinion, not be the default DI framework for ASP.NET. What's available right now is more than sufficient to do most tasks. If you need more functionality you can always use a different DI framework like StructureMap or AutoFac.
In the end it all comes down to what works for you. But stating this is either bad design or bad documentation is just wrong. You are of course free to prove me wrong on this. You could improve the ASP.NET documentation and/or would prove that the concept of inversion of control is wrong and suggest a better solution.

Does lots of controllers slows the performance? MVC

I want to ask a simple question about MVC controllers. I have googled a lot about controllers for "different controllers for each basic table", it cleared a lot of things but i have one question that i couldn't find answer for.
My question is that if i create controller for each basic table, lets say i have 10 basic tables that would create 10 controllers. So does lots of controller slows the application performance?
- In case, when going from view to controller.
- In case, when going from controller to another controller.
I am new so kindly be calm :)
Usually, one request is processed by one controller. And if it (cotroller) is small and have a few dependencies - it's quick. When you have one huge controller with many dependencies of other classes that have their own dependencies and so on... it could be a problem.
The Short Answer
No.
The Long Answer
The number of controllers doesn't have as much of a performance impact as how expensive each controller instance is to create.
The amount of overhead you might get for the number of controllers is negligible. Although the MVC framework uses .NET Reflection to identify the current controller type, it is optimized to look in the <Project Name>.Controllers namespace first. But this list is cached in a file, so after the first hit the performance is pretty good.
Where you might run into performance problems is when you do heavy processing within the controller constructor. The framework creates a controller instance for every request, so you should make it as cheap as possible to create a controller instance. If you follow a DI-centric (dependency injection) approach even if you are not actually using DI in your project, you will be able to keep the cost of creating a controller instance to a bare minimum.
What this means in plain English is - inject your dependencies into the constructor when the controller is created only. Don't actually do any processing in the constructor, defer that for the actual Action method call.
public interface IHeavyProcessingService
{
IProcessingResult DoSomethingExpensive();
}
public class HeavyProcessingService : IHeavyProcessingService
{
public HeavyProcessingService() {
}
public IProcessingResult DoSomethingExpensive() {
// Lots of heavy processing
System.Threading.Thread.Sleep(300);
}
}
public class HomeController
{
private readonly IHeavyProcessingService heavyProcessingService;
// The constructor does no heavy processing. It is deferred until after
// the instance is created by HeavyProcessingService.
// The only thing happening here is assignment of dependencies.
public HomeController(IHeavyProcessingService heavyProcessingService) {
this.heavyProcessingService = heavyProcessingService
?? throw new ArgumentNullException(nameof(heavyProcessingService));
};
public ActionResult Index()
{
var result = this.heavyProcessingService.DoSomethingExpensive();
// Do something with the result of the heavy processing
return View();
}
public ActionResult About()
{
return View();
}
public ActionResult Contact()
{
return View();
}
}
See this answer for more information.
If you do actually use a DI container in your application, you can improve performance even more by choosing the correct lifestyle of each dependency. If you can share the same dependency instance across multiple controller instances (singleton lifestyle), it makes the controller instance even cheaper to create.
What Backs said isn't necessarily true, either. The number of dependencies doesn't matter so much as how expensive those dependencies are to create. As long as the constructors are kept light and simple and the correct lifestyle is used for each dependency, performance won't be an issue regardless of the number of dependencies a controller has. That said, the controller shouldn't have more than about 5 direct dependencies - after that, you should refactor to aggregate services, making the dependency hierarchy more like an upside down pyramid rather than a flat set that are all injected into the controller.
It depends on the number of calls to controller.If you make frequent call to a controller for 2 to 3 table so it may get slow.Instead group that 3 table in one controller and call that.If your application needs to work in individual table than its fine,You will get response quiker.But if your application needs content from 2 to 3 tables than you have to call that 3 controller.So here the better way is to group that in one controller.
Hope you got the point

DDD and constructor explosion

I'm practicing DDD with ASP.NET MVC and come to a situation where my controllers have many dependencies on different services and repositories, and testing becomes very tedious.
In general, I have a service or repository for each aggregate root. Consider a page which will list a customer, along with it's orders and a dropdown of different packages and sellers. All of those types are aggregate roots. For this to work, I need a CustomerService, OrderService, PackageRepository and a UserRepository. Like this:
public class OrderController {
public OrderController(Customerservice customerService,
OrderService orderService, Repository<Package> packageRepository,
Repository<User> userRepository)
{
_customerService = customerService
..
}
}
Imagine the number of dependencies and constructor parameters required to render a more complex view.
Maybe I'm approaching my service layer wrong; I could have a CustomerService which takes care of all this, but my service constructor will then explode. I think I'm violating SRP too much.
I think I'm violating SRP too much.
Bingo.
I find that using a command processing layer makes my applications architecture cleaner and more consistent.
Basically, each service method becomes a command handler class (and the method parameters become a command class), and every query is also its own class.
This won't actually reduce your dependencies - your query will likely still require those same couple of services and repositories to provide the correct data; however, when using an IoC framework like Ninject or Spring it won't matter because they will inject what is needed up the whole chain - and testing should be much easier as a dependency on a specific query is easier to fill and test than a dependency on a service class with many marginally related methods.
Also, now the relationship between the Controller and its dependencies is clear, logic has been removed from the Controller, and the query and command classes are more focused on their individual responsibilities.
Yes, this does cause a bit of an explosion of classes and files. Employing proper Object Oriented Programming will tend to do that. But, frankly, what's easier to find/organize/manage - a function in a file of dozens of other semi-related functions or a single file in a directory of dozens of semi-related files. I think that latter hands down.
Code Better had a blog post recently that nearly matches my preferred way of organizing controllers and commands in an MVC app.
Well you can solve this issue easily by using the RenderAction. Just create separate controllers or introduce child actions in those controllers. Now in the main view call render actions with the required parameters. This will give you a nice composite view.
Why not have a service for this scenario to return a view model for you? That way you only have one dependency in the controller although your service may have the separate dependencies
the book dependency injection in .net suggests introducing "facade services" where you'd group related services together then inject the facade instead if you feel like you have too many constructor parameters.
Update: I finally had some available time, so I ended up finally creating an implementation for what I was talking about in my post below. My implementation is:
public class WindsorServiceFactory : IServiceFactory
{
protected IWindsorContainer _container;
public WindsorServiceFactory(IWindsorContainer windsorContainer)
{
_container = windsorContainer;
}
public ServiceType GetService<ServiceType>() where ServiceType : class
{
// Use windsor to resolve the service class. If the dependency can't be resolved throw an exception
try { return _container.Resolve<ServiceType>(); }
catch (ComponentNotFoundException) { throw new ServiceNotFoundException(typeof(ServiceType)); }
}
}
All that is needed now is to pass my IServiceFactory into my controller constructors, and I am now able to keep my constructors clean while still allowing easy (and flexible) unit tests. More details can be found at my blog blog if you are interested.
I have noticed the same issue creeping up in my MVC app, and your question got me thinking of how I want to handle this. As I'm using a command and query approach (where each action or query is a separate service class) my controllers are already getting out of hand, and will probably be even worse later on.
After thinking about this I think the route I am going to look at going is to create a SerivceFactory class, which would look like:
public class ServiceFactory
{
public ServiceFactory( UserService userService, CustomerService customerService, etc...)
{
// Code to set private service references here
}
public T GetService<T>(Type serviceType) where T : IService
{
// Determine if serviceType is a valid service type,
// and return the instantiated version of that service class
// otherwise throw error
}
}
Note that I wrote this up in Notepad++ off hand so I am pretty sure I got the generics part of the GetService method syntactically wrong , but that's the general idea. So then your controller will end up looking like this:
public class OrderController {
public OrderController(ServiceFactory factory) {
_factory = factory;
}
}
You would then have IoC instantiate your ServiceFactory instance, and everything should work as expected.
The good part about this is that if you realize that you have to use the ProductService class in your controller, you don't have to mess with controller's constructor at all, you only have to just call _factory.GetService() for your intended service in the action method.
Finally, this approach allows you to still mock services out (one of the big reasons for using IoC and passing them straight into the controller's constructor) by just creating a new ServiceFactory in your test code with the mocked services passed in (the rest left as null).
I think this will keep a good balance out the best world of flexibility and testability, and keeps service instantiation in one spot.
After typing this all out I'm actually excited to go home and implement this in my app :)

Clean Way to Test ASP.NET MVC Controller Without Hitting Database?

I'm trying to think of a good way to clean up my controllers to make them more testable without having to rely on a constant database connection. I thought I had a decent start by abstracting away my object context with an IObjectContext. This works well for the context, but my next problem is that I have a generic repository that I use in a number of action methods throughout my project (see code below).
In addition to the default constructor, my controller consists of an overload, which accepts an IObjectContext (simple dependency injection). In my unit tests, I can easily mock the IObjectContext. My issue is dealing with my generic repository in various action methods. I could add a number of additional constructor overloads to the controller, but I'm afraid this would get messy, really quickly. Short of doing that, however, I simply haven't been able to think of a clean way to improve testability so that I don't have to rely on a database connection.
Is there a simple solution that I'm overlooking?
/// <summary>
/// Initializes a new instance of the HomeController class
/// </summary>
public HomeController(IObjectContext context)
{
_context = context;
}
/// <summary>
/// GET: /home/index
/// </summary>
/// <returns>Renders the home page</returns>
public ActionResult Index()
{
List contacts;
HomeViewModel model;
using (IRepository<Contact> repository = new DataRepository<Contact>(_context))
{
contacts = new List(repository.GetAll());
}
model = new HomeViewModel(contacts);
return View(model);
}
If I have to go the route of adding additional constructor overloads to accommodate my concerns, I was considering adding a number of private properties (which would deffer instantiation of the repositories until they are needed) to my controllers for each of the repositories that action methods make use of. For example:
private IRepository<Contact> _contactRepository;
private IRepository<Contact> ContactRepository
{
get
{
return _contactRepository ?? (_contactRepository = new DataRepository<Contact>());
}
}
For unit testing purposes, I'd be able to pre-initialize the repositories using the constructor overloads.
What are your thoughts on this? Am I missing something cleaner that should be obvious?
First of all, get rid of your current Bastard Injection constructor overloads. With DI, you should only need one constructor, and that's the one that takes all the dependencies. (To enable the ASP.NET MVC run-time to create the Controllers, implement a custom IControllerFactory.)
The next step is to inject all your dependencies through the constructor. When you think it gets messy because there are too many constructor parameters, it's a good sign that you are violating the Single Responsibility Principle. When that happens, you extract an Aggregate Service.
Rinse and repeat :)
Well, I do what your final example shows all the time to inject mocks into my controllers. It does have a little smell to it (designing for testability), but it isn't bad coding and works great for testing.
Your use of a generic repository is more a dependency-cloaking device than a dependency injection. You should be able to see all of the dependencies a particular Controller uses: a generic repository hides this fact somewhere deep in the entrails of your Controllers which makes maintaining (and unit-testing) the code much more difficult. My suggestion: use concrete repositories.
You could also take a look at domain-driven design stuff.

Resources