Search code examples
c#genericsaccess-modifiers

How to control interaction between 2 classes (A & B) from 2 different assemblies?


I have an assembly (X), it is a library called DataItems, which contains my Model, with classes that represent business Objetcts like Order, Invoice, etc.. They all inherit from Class DataItem (A). A has method ResetStatus (M).

X is used by different other projects, so I can't change that much about this.

I have an assembly, a library called DataContext (Y) which references assembly X. It handles Database Connections etc. and instantiates objects of class A, fills them with Data from different sources etc. It must be able to call A.Resetstatus() (M).

Basically, I want all my front-end assemblies to reference and use DataContext (Y). But I don't want them to be able to use M.


Solution

  • Use an interface to expose just the methods that you choose.

    public interface IDataItem 
    {
        void OnlyUseThis();
    }
    
    public class DataItem : IDataItem
    {
        public void OnlyUseThis()
        {  
            // externaly available
        }
    
        public void ResetStatus()
        {
            // hands off
        }
    }
    

    Don't use DataItem externally, use IDataItem instead.

    Programmers will be able to get to the implementation if they really want to, but not by chance.