Inject different repository depending on a querystring / derive controller and inject the repository depending on the controller type / ASP.NET MVC

前端 未结 3 704
生来不讨喜
生来不讨喜 2021-01-13 13:36

I have a search form that can search in different provider. I started out by having a base controller

public SearchController : Controller
{

    protected r         


        
3条回答
  •  悲&欢浪女
    2021-01-13 14:10

    Whenever you need to vary a dependency based on a run-time value, Abstract Factory is the general solution.

    Instead of injecting ISearchService into your Controllers, inject an ISearchServiceFactory:

    public SearchController : Controller 
    { 
        private readonly ISearchServiceFactory searchServiceFactory;
    
        public SearchController(ISearchServiceFactory searchServiceFactory) 
        { 
            if (searchServiceFactory == null)
            {
                throw new ArgumentNullException("searchServiceFactory");
            }
    
            this.searchServiceFactory = searchServiceFactory; 
        } 
    
        public ActionResult Search(...) 
        { 
            // Use searchServiceFactory to create an ISearchService based on
            // run-time values, and use it to query and return a view. 
        } 
    } 
    

    It is not entirely clear to me which run-time value you need to vary on, but assuming that it's the Query, ISearchServiceFactory might be defined like this:

    public interface ISearchServiceFactory
    {
        ISearchService Create(Query query);
    }
    

提交回复
热议问题