da_jokker
da_jokker

Reputation: 1023

How do you prevent referencing program from accessing classes directly? (.NET)

I most likely didn't describe my Title correctly and am totally lacking the terminology for what I'm trying to do... so if you are reading this and know what I should be asking for.. please share.

So here is my issue. I am creating a DLL. This DLL will of course have several Classes inside. The calling solution will need access to those classes and their various methods.

However, I want to force the calling program to only create an instance of the "Parent\Root" class because I require certain information anytime they are going to use anything that is part of this class (think sort of like a license key but not really).

So from the Client view.. I want it to work like such..

FooDll.Client myFooClient = new FooDLL.Client(myLicensesKey)

myFooClient.Store.PlaceOrder()
myFooClient.Shop.FixWidget()

Now from my DLL side, I was thinking something like this...

public class Client
{
   public StoreLogic Store {get;}  //This is a internal Class that contains the method PlaceHolder
   public ShopLogic Shop {get;}    //This is an internal Class that contains the method FixWidget

   public Client(string LicenseKey)
   {
     set some internal global flags for the entire library
   }
 }

Now I can do this now as long as I declare the classes StoreLogic and ShopLogic as "Public". but if I do that, the client can now do this...

FooDll.StoreLogic myStore = new FooDLL.StoreLogic()

Which is what I don't want.

Upvotes: 0

Views: 39

Answers (1)

pfx
pfx

Reputation: 23214

Just mark the constructors of StoreLogicand ShopLogic as internal.
Doing so, only a class contained in the same assembly can instantiate these, like the Client class.

public class StoreLogic
{
    internal StoreLogic()
    {}

    public void PlaceOrder() {}
}

public class ShopLogic
{
    internal ShopLogic() 
    {}

    public void FixWidget() { }
}

public class Client
{
    public StoreLogic Store { get; }
    public ShopLogic Shop { get; }

    public Client(string LicenseKey)
    {
        this.Shop = new ShopLogic();
        this.Store = new StoreLogic();
    }
}

Upvotes: 3

Related Questions