Or K
Or K

Reputation: 335

How to expose a class to an external Project without Reference in c#

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!

Upvotes: 3

Views: 1401

Answers (1)

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:

Upvotes: 9

Related Questions