简体   繁体   中英

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

根据您的确切需求,您还可以考虑使用ILMerge将多个程序集合并为一个程序集。

You do not have to refrence p1 in p3 because just p2 uses p1's classes. You just have to deploy p1 library with p2 in your project. Most of the time visual studio will do it for you. You just need refrence p2 in p3 and all would be done.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM