3

I have 3 projects called A,B,C.

In project A I have class named "Car".

In project B I have reference to A, and in project B I create list of "Car".

Project C have reference to B.

I want to get the list from project B into project C and do something on it.

The problem:

In project C I don't allowed to do reference to project A where class "Car" on it, so project C don't know the "Car" class, and I can't do the next command:

List<Car> cars = B.GetCars();

Thanks for your help!

Or K
  • 335
  • 1
  • 5
  • 12
  • 1
    You can't return `Car` if project C cannot have a reference to the project of `Car`. You either have to add this reference or create a mapper class in project B – Tim Schmelter Aug 01 '16 at 08:08
  • The question is if there any other way to do that without reference to A and without a mapper class. Is B can expose "Car" class to C? – Or K Aug 01 '16 at 08:08
  • 1
    Um...Please can you clarify why `C` can't have a reference to `A`? You pretty much need one, so what precisely is stopping you, as that will be germane to the answer. – RB. Aug 01 '16 at 08:10
  • Also, do you actually need to be able to access members of `Car` in `C`? If not, you could just declare it as a `List` instead... – RB. Aug 01 '16 at 08:11
  • If you can, split A into A1 and A2, with A1 defining 'Car' and A2 (referencing A1) defining everything that you want to hide from C. Then you just reference A1 in C. – Patrice Gahide Aug 01 '16 at 08:12

1 Answers1

9

Solution Idea

I would use an Interface Layer for this (called Project I).

This Project I contains the interface ICar.

The other Projects A, B and C reference to I.

Your Car class should implement this interface and look something like this:

public class Car : ICar
{
    // ... some great Code
}

In Project B your function would be:

public List<ICar> GetCars()
{
   var myCars = new List<Car>();

   // ... some really special magic

   return (List<ICar>)myCars;
}

Now your code, in project C can use this function like this:

List<ICar> cars = B.GetCars();

Why using an Interface Layer?

Because then you will gain more maneuverability in your code. This is great for using Dependency Injection or Unit Tests. It will help you replace parts of your implementation in certain situations for example providing Mock objects during Unit Testing.


Design Approach

To prevent spaghetti code i would recommend to look up Jeffery Palermo's concept of Onion Architecture.

There are some great Question about it on SO:

Community
  • 1
  • 1