views:

45

answers:

4

I have a public class, MainObject that is in a class library (dll), for this example we will call it BaseLibrary.

I have a higher level class library that references the BaseLibrary to gain access to it's members. We will call this one DeviceLibrary.

I then have a Windows Forms Project, DeviceControl, in which I have added a reference to DeviceLibrary.

If I need to use a MainObject object, how do I do it? I know I can just add a second reference in the DeviceControl project to the BaseLibrary but I am just wondering if there is another way to access it through the DeviceLibrary? I am not sure what the laws of encapsulation dictate here...

+1  A: 

Any type to which you refer in your code must be part of a directly referenced assembly.

Although usually not practical, you can use the MainObject without directly referring to it by using a System.Object reference instead and using Reflection to call its members. In C# 4.0 you can probably just use the dynamic keyword:

dynamic x = MethodReturningAMainObject();
x.Foo(); //this will be compiled to use reflection to find "Foo"

Aside from using a dynamic or object reference, you can use any exposed base class or interface that applies to MainObject.

Mark Cidade
You _can_ use dynamic, but you (almost definitely) don't want to.
apollodude217
A: 

Disclaimer: This doesn't fully address your question.

Typically in a N-Tier design the "Models" span all layers. Here is one chart that I reference when designing: http://i.msdn.microsoft.com/cc700340.fig01_L(en-us).gif

I'm not sure what your BaseLibrary includes, but it seems like you may have to reference it from your DeviceLibrary.

Jerod Houghtelling
Useful diagram, have you got a link to the original context that came from?
Paolo
@Paolo http://msdn.microsoft.com/en-us/magazine/cc700340.aspx
Jerod Houghtelling
+1  A: 

If you are able to alter the contents of the library assemblies (i.e. it's your code), then you could either:

  1. Move MainObject into a separate reference assembly and have any of the existing assemblies reference it. This works well if MainObject is not actually dependent on the other contents of BaseLibrary.

  2. Extract an interface from MainObject and place that in a reference library that every other assembly can reference. Then is you code to the interface, you only need a reference to the new reference library.

If you can't alter the contents of the library assemblies, you could resort to writing a wrapper object for MainObject, with it's own interface and extract the interface to a reference library as in option 2.

Dr Herbie
+3  A: 

You have to add the reference. If you don't then the compiler will complain and tell you to add the reference. Using Reflection hacks should be a very distant second choice, it merely makes your code slow and still doesn't remove the runtime dependency on the DLL.

Hans Passant