试图理解继承链

时间:2017-03-01 08:30:46

标签: c# inheritance asp.net-web-api dependency-injection access-specifier

以下是Parent&儿童班。

public class ParentController : ApiController
{
   public ICustomer customer { get; set;}
   public ICustUtil util { get; set;}

}


public class ChildController : ParentController
{
    //no issue here
    public string Get()
    {
       customer = util.GetCustomers();
     }

}

如果我将父类属性设置为protected&尝试使用它们,我得到Object NULL reference Exception

public class ParentController : ApiController
{
   protected ICustomer customer { get; set;}
   protected ICustUtil util { get; set;}

}


public class ChildController : ParentController
{
    //Object Null reference exception at run time here
    public string Get(){
    customer = util.GetCustomers();}

}

我试图了解如何将public更新为protected访问说明符。

请注意: -

  
      
  • 我正在使用Castle Windsor DI容器
  •   

现在请忽略命名约定。

1 个答案:

答案 0 :(得分:2)

我猜你是通过像AutoFac这样的IoC容器实例化这些类的实例,而你正在使用setter注入。否则我无法看到第一个例子是如何工作的,因为你永远不会初始化util

当成员受到保护时,IoC容器无法初始化它。只有公共成员才能通过类本身之外的代码访问。