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:
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;
}
}
To achieve loose coupling I need to extract an interface and implement it using calls to NativeMethods:
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);
}
}
Now I can just use IFoo as a dependency in my code and mock it in tests:
public class Component : IComponent
{
public Component(IFoo foo, IService service) { ... }
}
Something seems wrong here. NativeMethods
must be internal according to FxCop. It makes sense then for IFoo
(which was extracted from NativeMethods
) 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: in order to achieve loose coupling I have to change the visibility of a component which otherwise would have been internal. What do you guys think about this?
Another problem: Component has method public void DoSomehing(Bar bar)
which uses the Bar
defined in NativeMethods.cs. I have to make that public too for this to work. This, or make a new Bar
class which wraps NativeMethods+Bar
. If I go the public way then NativeMethods
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...
It's possible that a public abstract class is your friend here, instead of an interface.
That can include internal abstract methods (referring to internal types), which actually makes it impossible to subclass in the normal way from outside the assembly (but InternalsVisibleTo
will let you create a fake for testing).
Basically interfaces haven't really been designed as well as they could have been from a component aspect.
This is exactly what I did in Noda Time for CalendarSystem
- its API uses internal types, but I wanted to make it an interface or abstract class. I wrote about the oddities of access in a blog post which you may find interesting.