开发者

C# Dependency Injection Sample

I was wondering if it makes sense to have objects inherit from a class that im开发者_开发问答plements the interface when dealing with dependency injections example

public interface IPeople
    {
        string Name { get; set; }
        int Age { get; set; }
        string LastName { get; set; }

    }

public class CPeople : IPeople
    {..implemented IPeople Methods..}

This way i only need to implement the interface in one place. I'm just not sure if this would be considered loosly coupled.

public class Dad : CPeople
    {
    }



public class Mom : CPeople
    {
    }

so that inside my controller i would have

public class Parent

{

    IPeople objMom;
    IPeople objDad;
    Parents m_Parent;

    public void factoryMethod()
    {

        objMom = new Mom();
        objMom.Age = 32;
        objMom.Name = "Jane";
        objMom.LastName = "Doe";

        objDad = new Dad();
        objDad.Age = 25;
        objDad.Name = "John";
        objDad.LastName = "Doe";

        m_Parent = new Parents(objMom,objDad);

    }
    public override string ToString()
    {                      
        return m_Parent.Mom.Name + " " + m_Parent.Mom.LastName +  " is " + m_Parent.Mom.Age + " years of age, " + m_Parent.Dad.Name + " " + m_Parent.Dad.LastName + " aged " + m_Parent.Dad.Age.ToString();
    }


Yes, this is considered loosely coupled since the controller does not need to have any knowledge of the inner objects beyond the interface definition.

If you care that Mom/Dad be kept separate, you could implement interfaces for just those (even if they are empty) and use those to ensure that parents is both a IMom and an IDad.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜