避免重写派生类的构造函数?

时间:2019-03-30 12:55:39

标签: c# oop

我有3个(不包括服务类)C#类及其构造函数,它们是使用依赖注入编写的(我使用的是 Microsoft Unity DI框架)如下:

public class BaseClass
{
    public ServiceClass1 Sc1 {get;set;}
    public ServiceClass2 Sc2 {get; set;}

    public BaseClass(
           ServiceClass1 sc1,
           ServiceClass2 sc2
    )
    {
       Sc1 = sc1;
       Sc2 = sc2;

       // assign C# Session value to property UserEmail for all Service classes that are passed in the Base class contructor
      SC1.UserEmail = (string) Session["UserEmail"];
      SC2.UserEmail = (string) Session["UserEmail"];
    }


}

public class DerivedClass1: BaseClass
{
    public DerivedClass1 (
           ServiceClass1 sc1,
           ServiceClass2 sc2
    ): base(sc1, sc2)
    {

    }
}

public class DerivedClass2: BaseClass
{
    public DerivedClass2 (
           ServiceClass1 sc1,
           ServiceClass2 sc2
    ): base(sc1, sc2)
    {

    }
}

问题是,每当使用新的Service类时,都必须将其添加到Base类的构造函数参数列表中,并且Derived类的构造函数参数列表需要更新,以便UserName属性新的服务类将被分配为其他先前的服务类。另外,必须将新的Service类类型的属性添加到基类中(我知道我无法避免将这样的新Service类属性添加到基类中)。我必须重新编写Base和Re类的构造函数,如下所示:

public class BaseClass
    {
        public ServiceClass1 Sc1 {get;set;}
        public ServiceClass2 Sc2 {get; set;}
        public ServiceClass3 Sc3 {get; set;} // added property

        public BaseClass(
               ServiceClass1 sc1,
               ServiceClass2 sc2,
               ServiceClass3 sc3 // added constructor parameter
        )
        {
           Sc1 = sc1;
           Sc2 = sc2;
           Sc3 = sc3; // added code line

           // assign C# Session value to property UserEmail for all Service classes that are passed in the Base class contructor
          SC1.UserEmail = (string) Session["UserEmail"];
          SC2.UserEmail = (string) Session["UserEmail"];
          Sc3.UserEmail = (string) Session["UserEmail"]; // added code line
        }


    }

    public class DerivedClass1: BaseClass
    {
        public DerivedClass1 (
               ServiceClass1 sc1,
               ServiceClass2 sc2,
               ServiceClass3 sc3 // added parameter
        ): base(sc1, sc2, sc3) // re-write passing arguments
        {

        }
    }

    public class DerivedClass2: BaseClass
    {
        public DerivedClass2 (
               ServiceClass1 sc1,
               ServiceClass2 sc2,
               ServiceClass3 sc3 // added parameter
        ): base(sc1, sc2, sc3) // re-write passing arguments
        {

        }
    }

我的问题:每当在基类的构造函数中添加新的Service类时,如何避免修改Derived类的构造函数?

1 个答案:

答案 0 :(得分:0)

解决此问题的唯一方法是不使用构造函数来定义依赖项。某些依赖注入框架(例如AutoFac)支持property injection

那样,您不需要构造函数来设置依赖项,而是依赖关系注入框架会为您设置依赖项属性。

这样做的缺点是,如果您在没有依赖注入框架的情况下创建实例,或者不初始化属性注入,那么您“必须知道”,必须设置依赖属性,因为没有强制您设置它们的构造函数。