circular dependencies between dlls with visual studio

前端 未结 9 1123
忘掉有多难
忘掉有多难 2020-12-15 08:00

I have a circular dependency between two functions. I would like each of these functions to reside in its own dll. Is it possible to build this with visual studio?



        
9条回答
  •  無奈伤痛
    2020-12-15 08:36

    You need to decouple the two DLLs, placing the interfaces and implementation in two different DLLs, and then using late binding to instantiate the class.


    // IFoo.cs: (build IFoo.dll)
        interface IFoo {
          void foo(int i);
        }
    
        public class FooFactory {
          public static IFoo CreateInstance()
          {
            return (IFoo)Activator.CreateInstance("Foo", "foo").Unwrap();
          }
        }
    

    // IBar.cs: (build IBar.dll)
        interface IBar {
          void bar(int i);
        }
    
        public class BarFactory {
          public static IBar CreateInstance()
          {
            return (IBar)Activator.CreateInstance("Bar", "bar").Unwrap();
          }
        }
    

    // foo.cs: (build Foo.dll, references IFoo.dll and IBar.dll)
        public class Foo : IFoo {
          void foo(int i) {
            IBar objBar = BarFactory.CreateInstance();
            if (i > 0) objBar.bar(i -i);
          }
        }
    

    // bar.cs: (build Bar.dll, references IBar.dll and IFoo.dll)
        public class Bar : IBar {
          void bar(int i) {
            IFoo objFoo = FooFactory.CreateInstance();
            if (i > 0) objFoo.foo(i -i);
          }
        }
    

    The "Factory" classes are technically not necessary, but it's much nicer to say:

    IFoo objFoo = FooFactory.CreateInstance();
    

    in application code than:

    IFoo objFoo = (IFoo)Activator.CreateInstance("Foo", "foo").Unwrap();
    

    because of the following reasons:

    1. You can avoid a "cast" in application code, which is a good thing
    2. If the DLL that hosts the class changes, you don't have to change all the clients, just the factory.
    3. Code-completion still wroks.
    4. Depending on your needs, you have to call culture-aware or key-signed DLLs, in which case you can add more parameters to the CreateInstance call in the factory in one place.

    -- Kenneth Kasajian

提交回复
热议问题