class structure for decoupling and dependency inje

2019-08-27 01:42发布

I am writing a windows service and I would like to use an IoC container for resolving dependencies in some of my classes. I have the following simple scenario.

    public partial class serviecclass: ServiceBase
        {
           protected override void OnStart(string[] args)
            {
                StartServer();
            }

            public void StartServer()
            {
              //create class A 
             // do not have an interface for ClassA as in my app there will only be    //one  Version of ClassA
               var classa=new ClassA();
               classa.DoWork();

            }
        }

    public ClassA
    {

       public ClassA()
       {

       }

       public void DoWork()
      {
         // first do some work
         //then call class b to do more work
               var classb=new ClassB(?,?,new ClassE);
               classb.DoOtherWork();
      }
    }


    public ClassB
    {
       private IClassC _dependency1;
       private IClassD _dependency2;           
       // do not have an interface for ClassE as in my app there will only be one 
       // version of ClassE
       private ClassE _classe 
       public ClassB(IClassC c,IClassD d,ClassE e)
       {
          _dependencyc=c;
          _dependencyd=d;
          _classe =e;
       }

       public void DoOtherWork()
      {
         // do other work

      }
    }

In ClassA although it does not have a direct dependency on ClassC and ClassD is it still considered as having a dependency on ClassC and ClassD because i need to pass instances of IClassC c,IClassD when i create a new ClassB inside of ClassA?

do i need an interface for ClassA and ClassB just because ClassA depends on ClassB and serviceclass depends on ClassA(although i will never have different versions of ClassA and ClassB in my application)?

If i a use an IoC container to inject IClassC and IClassD into ClassB how do i create ClassB inside ClassA? var classb=new ClassB(?,?,new ClassE);

Thankyou for your patience. hope my question makes sense. I am just trying to understand how the whole concept of DI and Ioc works.

1条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-08-27 02:16

For the best dependency injection, I would recommend:

   public ClassA
    {
      private IClassB _classB;

       public ClassA(IClassB classB)
       {
          _classB = classB;
       }

       public void DoWork()
      {
         // first do some work
         //then call class b to do more work
               _classB.DoOtherWork();
      }
    }

Also, I would go ahead and create an interface for ClassE. Even if you aren't going to use it for your code, you can (and probably should) use it for your unit testing.

查看更多
登录 后发表回答