使用Composition在C#中自动生成Wrapper类

010*_*101 10 c# visual-studio

这应该很简单,但我找不到任何东西.

我在一个程序集中有一个类(一个共享库 - 它是一组Web服务的代理类)我在另一个程序集中有一个类(Web项目)

在代理程序集中有一个名为"Profile"的类.有一组类在Web项目中"使用"一个Profile.如果没有用户登录,则使用GenericProfile.

遵循"关注点分离"的原则....代理程序集由其他项目使用,并且仅关注Web服务的东西.网络项目只有网络内容

但是,现在需要一个"GenericProfile" - 将其视为"访客用户".

逻辑上要做的是构建一个名为IProfile的接口,并使两个类从它派生.但这会在两个程序集之间产生循环依赖关系.

下一个最好的想法是创建一个名为MyInterfaces的第三个程序集并将IProfile放在那里 - 但是在我看来这会导致违反"关注点分离"原则.至少,这个问题的一个例子似乎太小,不能在我的解决方案中制作额外的模块.

输入包装类 - 或复合包装类(无论你想调用它)

我正在寻找一些最终产生如下内容的东西.是否有工具或Visual Studio扩展程序可以执行此操作?也许是.tt文件?

namespace WebProject
{
   public interface IProfile
   {...}

   class MyWrapperClass : IProfile
   {
       Proxy.Profile _profile;

       public MyWrapperClass(Proxy.Profile proxy)
       {
           _profile = proxy;
       }

       public string IProfile.Property1{ get { return _profile.Property1; } set { _profile.Property1 = value; } }
       public string IProfile.Property2{ get { return _profile.Property2; } set { _profile.Property2 = value; } }
       public string IProfile.Property3{ get { return _profile.Property3; } set { _profile.Property3 = value; } }
   }

}
Run Code Online (Sandbox Code Playgroud)

小智 5

在 Visual Studio 2017 中

创建你的班级

namespace WebProject
{
   public interface IProfile
   {...}

   class MyWrapperClass : IProfile
   {
      private IProfile _wrapped;
   }
}
Run Code Online (Sandbox Code Playgroud)

将光标定位在类 MyWrapperClass 的 IProfile 上:IProfile 并点击 ctrl-。选择通过_wrapped 实现接口。不需要 ReSharper。


Tar*_*aal 0

如果我遇到你原来的问题,我会把IProfile你的共享库与Profile课程一起放入。然后,您的 Web 项目可以实现GenericProfile它需要的类,不需要了解任何其他内容,并且库的其他客户端可以根据需要执行相同的操作。它对于测试库也很有用。