ApiController and Controll inherit from same base class - asp.net-mvc

I have multiple controllers and apicontrollers in my project.
How to make both types of controllers inherit a base class, as there is more than some methods, that I need in both?

Composition might be a better option.
Basically instead of inheriting to gain the functionality stick it in a common class, that can be included as a property in both the Api and standard controller.
You can then inject the dependancy into both.
For example:
public class CommonControllerLogic : ICommonControllerLogic
{
public ActionResult SomeSortOfMethod()
{
// etc..
}
}
public class MobileApiController: ApiController
{
public ICommonControllerLogic CommonControllerLogic {get;set;}
// etc..
}
public class HomeController: Controller
{
public ICommonControllerLogic CommonControllerLogic {get;set;}
// etc..
}
Composition is often favoured over inheritence, there are loads of articles on it, just do a quick google search, have a read of this article.

MVC controllers inherit from Controller, whereas API controllers inherit from ApiController. C# does not support multiple inheritance easily. I would recommend moving the shared logic into a static class that both can call. Otherwise you could provide more detail about what is shared; in some cases other design patterns may be more appropriate.

Related

What is the difference between ComponentModel.DataAnnotation and decorator pattern.?

I was implementing repository decorator pattern on my project as:
[Auditable]
public class Product
{
public int Id {get; set;}
public string Name {get; set;}
}
I got this idea from the following link.
https://efpatterns.codeplex.com/discussions/282699
But couldn't successfully implemented. Then I start learning about decorator pattern and DataAnnotation because the way Auditable attribute on Product entity is somewhat similar in DataAnnotation and decorator pattern. So my question is are they same thing.? If they are the same then how would I implement Auditable repository pattern (more on link) on my project.
That's not the decorator pattern as originally described by the Gang Of Four.
The decorator pattern is an inheritance technique to add functionality to existing classes. The pattern works by creating a set of subclasses which each provide a specific type of functionality on top of the base class.
Then you compose a combination by passing the existing instance as inner object to a subclass instance:
public class SecurityToken
public class ExpiringToken : SecurityToken;
public class RpcSecurityToken : SecurityToken;
So if you would like to have a token which is remote and will expire after an amount of time:
var token = new RpcSecurityToken(new ExpiringToken(new SecurityToken("sds")));
What you do is to just decorate a class with an attribute, which not is the same thing.
The decorator pattern is a mechanism of taking a base implementation of a given interface as extending its behavior without modification of original implementation.
Its similar to inheriting from a base class, however it has more flexibility. For example, a decorator class can be applied to any other class that implements the same interface, there is no restriction to only extending a single base class. They can also be chained together etc...
e.g
public interface IThing
{
void AMethod()
}
public abstract class ThingDecorator : IThing
{
private IThing inner;
public ThingDecorator(IThing inner)
{
this.inner = inner;
}
public virtual void AMethod()
{
this.inner.AMethod();
}
}
Inheriting from ThingDecorator and applying your own extension to the virtual AMethod will add behavior (decorate) the inner instance that is passed in. As the inner instance is coupled to an interface it can be any implementation of that interface.
In your example, you could inherit ThingDecorator as AuditThingDecorator, and override AMethod and include Audit features before you call the base.AMethod()
This is different to just applying an attribute to a class. I think you are trying to apply behavior with an attribute. Attributes can only apply behavior to the class if there is a container, or some other part of the system that can read them and actually apply given behavior. With DataAnnotations, there are other classes that read these attributes and apply behavior (for example, within ASP.NET MVC, the DefaultModelBinder use some of the attributes to provide validation when binding the model).
This is a AOP (apsect orientated programming) approach. One way to apply this (and a way I tend to use) is to use Castle.Core and create interceptors that can automatically implement interface methods or extend virtual methods and read attributes from the Methods/properties that are intercepting, and then apply behavior:
http://docs.castleproject.org/Tools.DynamicProxy-Introduction.ashx
They are both essentially proxies of a given type, however the Decorator pattern above is not dynamic, they are created within code, and the AOP approach can apply behavior at runtime.

Multiple BaseControllers with IoC

I read this question, and the answer helps me but not completely. What if I have 20 repositories with different responsibilities, like for example:
ICountryRepository
ICityRepository
and
IUserRepository
IPersonRepository
I can have all the methods of this repositories in the BaseController, but I would prefer something like having a TerritoriesBaseController, whit the ICoutnryRepository and ICityRepository and PersonsBaseController IUserRepository and IPersonRepository, than inherits from BaseController.7
My problem is that, if I have a controller that wants to use the TerritoryBaseController and PersonBaseController, I can't make it inherit from both controllers.
The reason why I want to separate the base controllers, is for structure, order and for not having a controller with 200 methods, but 20 controllers with 10 methods, and with separated responsibilities.
Some ideas how can it be organized?
EDIT:
I think I didn't explain the question properly.
Let's take this example:
I have a project with IoC, and let's say I have 4 repositories.
ICountryRepository, ICityRepository, IUserRepository, IPersonRepository.
I have a controller that needs methods of the 4 repositories, for example, UserController, it will use IUserRepository and IPersonRepository to save the user, and ICountryRepository and ICityRepository to show a list of countries and cities that the user has to select.
I also have a BaseController, where i have the generic methods of the controllers, and UserController inherits of BaseController, so:
UerController : BaseController
What I would like to do is, have a TerritoriesBaseController, where i would have all the methods that are repeated in my controlers of ICouuntrRepository and ICityRepository, like:
public JsonResult GetCountriesSelectList()
{
List<Country> listCountryLanguage = _applicationCountry.GetAll().ToList();
return Json(new SelectList(listCountryLanguage, "IdCountry", "Name"), JsonRequestBehavior.AllowGet);
}
And the same with IPersonRepository and IUserRepository, with a UserBaseController.
But I Can't use:
Usercontroler : BaseController, TerritoriesBaseController, UserBaseController
Because in c# you can only inherit from one class.
How can i reorganize it or what solution can I use?
What if I have 20 repositories with different responsibilities,
If you have a controller that needs to use 20 repositories, there is something wrong with your design. That controller will violate the Single Responsibility Principle.
There are a few solutions to this problem:
Split the logic in the controller up into multiple smaller, more focused controllers that each have just a few dependencies.
Move part of the logic to an aggregate service. In your case your controller probably has a lots of business logic in it. You should extract that business logic to a different class. The command/handler pattern is very suited for implementing business logic.
If you have code that uses multiple repositories, there's a special well-known pattern that for this: the Unit of Work pattern. What you can do is make those repositories accessible as properties on a Unit of Work class and inject only that unit of work.
UPDATE
UserController, it will use IUserRepository and IPersonRepository to
save the user, and ICountryRepository and ICityRepository to show a
list of countries and cities that the user has to select.
In that case you should extract the logic of saving the user into a new class and you should do the same with the logic for getting the list of countries. In that case your UserController will only depend on two more specific dependencies and the code inside the UserController will be minimized.
Don't use base controllers. Using base classes is often a sign of a glitch in your design. Your code becomes much harder to test when using base classes, and those base classes will often grow into god classes. Besides, you already noticed that multiple inheritance is not possible in .NET.
So what you can do is the following:
public class UserController : Controller
{
private ICommandHandler<SaveUser> saveUserHandler;
private IQueryProcessor queryProcessor;
public UserController(ICommandHandler<SaveUser> saveUserHandler,
IQueryProcessor queryProcessor)
{
this.saveUserHandler = saveUserHandler;
this.queryProcessor = queryProcessor;
}
public ActionResult Save(SaveUserViewModel model)
{
this.saveUserHandler.Handle(new SaveUser
{
UserId = model.UserId,
Name = model.UserName,
});
Redirect("/Success");
}
public JsonResult Countries()
{
var listCountryLanguage = queryProcessor.Execute(new GetAllCountries());
return Json(new SelectList(listCountryLanguage, "IdCountry", "Name"),
JsonRequestBehavior.AllowGet);
}
}
Do note that for this example I use the query/handler and command/handler patterns, but that's optional.

proper way of designing controller for an MVC 4 application

I have a simple model with menu and menuItem which both inherit from an abstract class.
I have created an adminController which can do CRUD operations.
which I've stuck here is that should create controller for menu and menuItem?
because both menu and menuItem are both inherit from a same type.
meanwhile their corresonding views for a method like Edit() can have different appearance.
I mean I have to check in views to know I'm trying to Edit Menu or MenuItem
but if I implement controller for each entity, I have duplicate code.
so what is the best approach for designing controller for this kind of operations?
For what it's worth, controllers are just classes, which means they can be inherited from. So, you can simply do:
public class MenuController : Controller
{
// all the actions here
}
public class MenuItemController : MenuController
{
}
Based on the naming conventions, then, you can apply different views to the actions per controller simply by putting them in their respective view directories: "Menu" and "MenuItem", respectively.
If you need to change a particular action method in the subclassed controller, just make the action virtual in MenuController and then override it in MenuItemController:
public class MenuController : Controller
{
public virtual ActionResult SomeActionToOverride() { ... }
}
public class MenuItemController : MenuController
{
public override ActionResult SomeActionToOverride() { ... }
}
This is all just basic OOP.
The answer, unfortunately, is "It Depends".
You could dispatch to different views based on the object type, from the same Menu controller, with the common operations on the controller, with the views calling the same HttpPost actions with a type-discriminating property. This is a design which exposes the OO architecture to the public API surface.
Or, as these are separate domain entities, you could expose two controllers with their own suite of CRUD operations and have a more REST like API surface.
Duplicate code to provide independent endpoints or security policy differentiation at what amounts to a public API surface is less of a smell than elsewhere.

where to keep frequently used methods in MVC

I need to implement MVC architecture in my company, So can anyone suggest where to keep frequently used methods to call on all pages. Like:
states ddl, departments ddl also roles list and etc...
Please give me suggestions where to keep them in architecture.
Thanks
There are different solutions depending on the scale of your application. For small projects, you can simply create a set of classes in MVC application itself. Just create a Utils folder and a DropDownLists class and away you go. For simple stuff like this, I find it's acceptable to have static methods that return the data, lists, or enumerations you require.
Another option is to create an abstract MyControllerBase class that descends from Controller and put your cross-cutting concerns in there, perhaps as virtual methods or properties. Then all your actual controllers can descend from MyControllerBase.
For larger applications, or in situations where you might share these classes with other MVC applications, create a shared library such as MySolution.Utils and reference the library from all projects as required.
Yet another possibility for larger solutions is to use Dependency Injection to inject the requirements in at runtime. You might consider using something like Unity or Ninject for this task.
Example, as per your request (also in GitHub Gist)
// declare these in a shared library
public interface ILookupDataProvider
{
IEnumerable<string> States { get; }
}
public class LookupDataProvider: ILookupDataProvider
{
public IEnumerable<string> States
{
get
{
return new string[] { "A", "B", "C" };
}
}
}
// then inject the requirement in to your controller
// in this example, the [Dependency] attribute comes from Unity (other DI containers are available!)
public class MyController : Controller
{
[Dependency]
public ILookupDataProvider LookupDataProvider { get; set; }
public ActionResult Index()
{
var myModel = new MyModel
{
States = LookupDataProvider.States
};
return View(myModel);
}
}
In the code above, you'll need to configure your Dependency Injection technology but this is definitely outside the scope of the answer (check SO for help here). Once configured correctly, the concrete implementation of ILookupDataProvider will be injected in at runtime to provide the data.
One final solution I would suggest, albeit this would be very much overkill for small projects would be to host shared services in a WCF service layer. This allows parts of your application to be separated out in to highly-scalable services, should the need arise in the future.

Where should 'CreateMap' statements go?

I frequently use AutoMapper to map Model (Domain) objects to ViewModel objects, which are then consumed by my Views, in a Model/View/View-Model pattern.
This involves many 'Mapper.CreateMap' statements, which all must be executed, but must only be executed once in the lifecycle of the application.
Technically, then, I should keep them all in a static method somewhere, which gets called from my Application_Start() method (this is an ASP.NET MVC application).
However, it seems wrong to group a lot of different mapping concerns together in one central location.
Especially when mapping code gets complex and involves formatting and other logic.
Is there a better way to organize the mapping code so that it's kept close to the ViewModel that it concerns?
(I came up with one idea - having a 'CreateMappings' method on each ViewModel, and in the BaseViewModel, calling this method on instantiation. However, since the method should only be called once in the application lifecycle, it needs some additional logic to cache a list of ViewModel types for which the CreateMappings method has been called, and then only call it when necessary, for ViewModels that aren't in that list.)
If you really don't want to use a bootstrapper, then at least a static constructor is an easy way of ensuring your CreateMap is called at most once. (With less messing around and more thread proof than Jonathon's answer.)
public class AccountController : Controller
{
static AccountController()
{
Mapper.CreateMap<Models.User, ViewModels.UserProfile>();
Mapper.CreateMap<Models.User, ViewModels.ChangePassword>();
}
}
If you use profiles, you can place all of your "CreateMap" calls there. Additionally, you can create a static bootstrapper class that contains your configuration, and have the startup piece just call the bootstrapper.
OK, the way I'm currently doing it is this:
I add some logic to the constructor of my BaseController, which runs the 'CreateMappings' method, but only once per Controller Type:
public abstract class BaseController : Controller
{
public BaseController()
{
if (!controllersWithMappingsCreated.Contains(GetType()))
{
CreateMappings();
controllersWithMappingsCreated.Enqueue(GetType());
}
}
protected virtual void CreateMappings() { }
}
In each concrete controller, I use CreateMappings to declare the mappings for all the Models/ViewModels relevant to that controller.
public class AccountController : BaseController
{
public AccountController() : base() { }
protected override void CreateMappings()
{
Mapper.CreateMap<Models.User, ViewModels.UserProfile>();
Mapper.CreateMap<Models.User, ViewModels.ChangePassword>();
}
}
I also found some interesting alternatives involving Attributes here and here, however they strike me as a bit overcomplicated.

Resources