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

前端 未结 3 1655
执念已碎
执念已碎 2021-01-15 17:23

I have alluded to this issue in my other question, but i think it\'s worthwhile breaking it out into its own question, as it\'s not really dependant on the other scenarios i

相关标签:
3条回答
  • 2021-01-15 17:38

    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'

    0 讨论(0)
  • 2021-01-15 17:43

    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.

    0 讨论(0)
  • 2021-01-15 17:59

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

     [assembly: InternalsVisibleTo( "MyCompany.MyProject.Repositories" )]  
    
    0 讨论(0)
提交回复
热议问题