Asp.Net MVC - general data for all controllers

Setup: (using Asp.Net MVC 2 RC, Entity Framework, SQL Server, VS2008)

My friend and I are working on a project that will have different domains pointing to it. We want to get the domain (website) from the Request and use it to manage the data. Website data must be part of all controllers.

Ex. The data for domain1.website.com will be different from the data for domain2.website.com, and it will be different from the data for website2.com. The appearance of the site is the same for all this, but the data is different.

I installed BaseController from which all my other controllers are inherited. But I do not like it.

BaseController:

public class BaseController : Controller { private Website _website; private readonly IWebsiteRepository _websiteRepository; public BaseController(IWebsiteRepository websiteRepository) { _websiteRepository = websiteRepository; } public Website CurrentWebsite { get; } } 

The problem is that now I need to pass the IWebsiteRepository to the base of each of my controllers:

 public class BioController : BaseController { private readonly IBiographyRepository _bioRepository; public BioController(IBiographyRepository bioRepository, IWebsiteRepository websiteRepository) : base(websiteRepository) { _bioRepository = bioRepository; } } 

HERE IS MY QUESTIONS

  • Is there a better way to handle multiple domains pointing to a single project and filtering data?
  • Is there a better way to have a site object in every controller?

UPDATE

Sorry, I forgot to add this. I already use IoC (structural map). My question is more consistent:

  • Should I replace BaseController with something else? Actionfilter?
  • Is there a way to configure it, so I did not have to pass the IWebsiteRepository to the base class?
  • Is there a better way to handle the domains used for data?
+4
source share
2 answers

I really like the idea of โ€‹โ€‹entering the repository through the constructor installation. This will simplify the testing of controllers, as you can simply transfer to the repository. An alternative would be to use the static factory class to get the repository from the request, but using static classes would make unit testing more difficult.

One of the improvements I would make is to create a default constructor for your controllers, which invokes a constructor with parameters with zero values. In your constructor with parameters, create an instance of the correct repository if the specified parameter is zero. Thus, you do not need to implement a factory controller to build controllers with their parameters; The factory default controller can use parameterless constructors, and you still benefit from the injection of the constructor.

  public BaseController() : this(null) { } public BaseController( IWebsiteRepository websiteRepository ) { this._websiteRepository = websiteRepository ?? new WebsiteRepository(); } 
+1
source

Source: https://habr.com/ru/post/1299342/


All Articles