title: Loose coupling NativeMethods
body: <p>I need to use a native DLL from C#. The DLL exposes several methods which I can access via P/Invoke, and several types. All this code is in a standard NativeMethods class. To keep things simple it looks like this:</p>
  
  <pre><code>internal static class NativeMethods
  {
      [DllImport("Foo.dll", SetLastError = true)]
      internal static extern ErrorCode Bar(ref Baz baz);
  
      internal enum ErrorCode { None, Foo, Baz,... } 
  
      [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
      internal struct Baz
      {
          public int Foo;
          public string Bar;
      }
  }
  </code></pre>
  
  <p>To achieve loose coupling I need to extract an interface and implement it using calls to NativeMethods:</p>
  
  <pre><code>public interface IFoo
  {
      void Bar(ref Baz baz);
  }
  
  public class Foo : IFoo
  {
      public void Bar(ref Baz baz)
      {
           var errorCode = NativeMethods.Bar(baz);
           if (errorCode != ErrorCode.None) throw new FooException(errorCode);
      }         
  }
  </code></pre>
  
  <p>Now I can just use IFoo as a dependency in my code and mock it in tests:</p>
  
  <pre><code>public class Component : IComponent
  {
       public Component(IFoo foo, IService service) { ... }
  }
  </code></pre>
  
  <p>Something seems wrong here. <code>NativeMethods</code> must be internal according to FxCop. It makes sense then for <code>IFoo</code> (which was extracted from <code>NativeMethods</code>) to be internal too. But I can't just make it internal b/c it is used in a public ctor (which should stay public). So: <em>in order to achieve loose coupling I have to change the visibility of a component which otherwise would have been internal.</em> What do you guys think about this?</p>
  
  <p>Another problem: Component has method <code>public void DoSomehing(Bar bar)</code> which uses the <code>Bar</code> defined in NativeMethods.cs. I have to make that public too for this to work. This, or make a new <code>Bar</code> class which wraps <code>NativeMethods+Bar</code>. If I go the public way then <code>NativeMethods</code> becomes public too and FxCop complains that "Nested types should not be visible". If I go the wrapper way... well, I feel it's too much of an effort to do it for all the "native types". Oh, there is the 3rd way: move the types away from NativeMethods and make them public. Then FxCop gets to analyze them and finds all the errors which were otherwise hidden when they were nested in NativeMethods. I really don't know what's the best way here...</p>