Dependency Injection - When to use property injection

后端 未结 2 1520
情书的邮戳
情书的邮戳 2021-02-08 08:42

I\'ve a class which have a constructor like this:

    private string _someString;
    private ObjectA _objectA;
    private ObjectB _objectB;
    private Diction         


        
2条回答
  •  逝去的感伤
    2021-02-08 09:28

    You should use property injection (or setter injection) when object creation of your type is out of your control. Like aspx Page, HttpHandler, ApiController etc. For all others situations it is recommended to use constructor injection.

    To resolve dependencies for aspx Page using StructureMap, i use the following approach.

    First, I create a BasePage class and use StructureMap's BuildUp() method in the constructor to resolve dependencies of the derived pages. Code is given below:

    public class BasePage : Page
    {
        public BasePage()
        {
            // instruct StructureMap to resolve dependencies
            ObjectFactory.BuildUp(this);
        }
    }
    
    public class Default : BasePage
    {
         public ICustomerService customerService { get; set; }
    
         protected void Page_Load(object sender, EventArgs e)
         {
             // can start using customerService
         }
    }
    
    public class Login : BasePage
    {
         public IAuthenticationService authenticationService { get; set; }
    
         protected void Page_Load(object sender, EventArgs e)
         {
             // can start using authenticationService
         }
    }
    

提交回复
热议问题