How can i hide “setters” from all but one assembly?

帅比萌擦擦* 提交于 2019-12-01 09:40:28

you could make the setter internal, and make the internals visible to the repository assembly

[assembly: InternalsVisibleTo("MyLibrary.Repositories")]
public class Post
{
   public int PostId { get; internal set; }
   public int Name { get; internal set; }
      ...
}

This means that everything can 'get' those properties, but only this assembly, and the assembly containing the repository, can 'set'

Mark all your setters as internal, then add the InternalsVisibleTo Attribute to your POCOs assembly:

 [assembly: InternalsVisibleTo( "MyCompany.MyProject.Repositories" )]  
Matt Kocaj

Luke Schafer's is a good answer. It satisfies the technical requirement of the question. But I'd advise caution simply because this may not address the problem in the future.

Not to suggest over engineering but perhaps you might want to think about abstracting away further what you are doing with these objects that have the settable ID property. It may suffice to create this 'visibility' with this attribute decoration but i think it's sort of a hack for the problem. It might be cleaner to encapsulate the interaction between these objects with something else, thus removing the setter access from consuming code.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!