Andrey Andreev Andrey Andreev - 1 month ago 4
C# Question

C# encapsulate project references

Let's say I have projects P1, P2, and P3.

P2 has reference to P1 and its classes use P1's classes. Meanwhile P3 has reference to P2 and its classes use P2's classes that use P1's classes.

To make it work I need to reference both P1 and P2 in P3. Is there any way to encapsulate the classes of P1 to P2 (so P3 needs to reference just P2)?


May be it's because your project P3 uses types of P1? Since in the example bellow, when P2 types uses types of P1 internally - everything works just fine. Or just one another option: you can extract common models to a separate library.

Let's say you have next in P1

public class P1_Model {
    public string Name {
        get { return "1"; }

public class P1_Service {
    public static P1_Model Execute() {
        return new P1_Model();

and P2

public class P2_Service {
    public static P2_Model Execute() {
        var p1Model = P1_Service.Execute();
        return new P2_Model(p1Model);

    public class P2_Model {
        public P2_Model(P1_Model p1Model) {
            Model = p1Model;

        public string Name {
            get { return Model.Name; }

        public P1_Model Model { get; }

And here is P3

var p2Model = P2_Service.Execute();

Console.WriteLine(p2Model.Name); //works fine. No Reference to P1 needed
Console.WriteLine(p2Model.Model.Name); // requires P1 reference from P3