Search code examples
c#asp.net-mvcasp.net-apicontroller

Setting Parameters before api Controller initializes


I'm trying to pass a parameter for database connection purposes in my apiController constructor. for example by default in my baseAPIController i neeed the code to be '1'. But in this specific controller I need to change that parameter to '7'. The problem is that my BaseAPIController instanciates with '1' and after instantiated even if I send '7' in the property it doesn't change. How can I set "7" in this specific controller before the baseAPI is initialized?

public class ListagemProjetoEletricoWebController :BaseAPIController<ListagemProjetoEletricoBusiness>
{       
    public List<ListagemProjeto> Get(String cpf)
    {
        business.idEmpresa = 7;
        List<ListagemProjeto> listProjetoEletricoWeb = business.GetProjetoEletricoLista(cpf);
        return listProjetoEletricoWeb;
    }
}

and in my baseAPIcontroller I have.

protected override void Initialize(HttpControllerContext controllerContext)
{
    this.business = new TBusiness();
    this.business.idEmpresa = 1;

    this.business.db = new BaseBusiness(this.business.idEmpresa).db; 

    base.Initialize(controllerContext);
}

Solution

  • Create an virtual property in your base class to represent the idEmpresa

    public class BaseAPIController
    {
         //Set the default to whatever it is used normally
         public virtual int idEmpresa { get {return 1;} }
    }
    

    then in your derrived class you override that property

    public class ListagemProjetoEletricoWebController :BaseAPIController<ListagemProjetoEletricoBusiness>
    {
        public override int idEmpresa { get { return 7;} } 
    }
    

    Then when you set your business idEmpresa use the property instead

    this.business.idEmpresa = this.idEmpresa;