jeudi 16 novembre 2017

How to access internals from class references via interface

I have the situation that i have two classes living in different assemblies. Assembly B references Assembly A and Class B needs access to an internal method of Class A (internal so that other users of Class A dont have access, not for security, just to prevent misuse). I control both assemblies, so InternalsVisibleTo is possible to only grant Class B access.

Assembly A

[assembly: InternalsVisibleTo("B")]
public Class A {
...
    internal String secretKey { get; set;}
}

Assembly B

public Class B {
...
    // use A.secretKey which works just fine
}

Actually, was possible because i now need to reference Class A via a newly added (actually autogenerated by Visual Studio) Interface IA.

Assembly A

public interface IA {
    // nothing gets generated for secretKey because its internal
}

[assembly: InternalsVisibleTo("B")]
public Class A : IA {
...
    internal String secretKey { get; set;}
}

Assembly B

public Class B {
...
    // how to use IA.secretKey 
}

So the question is, how can i still grant access to the internal method of Class A to only Class B but not expose it in the interface IA? Is this a nogo or what is best practise?

Is reflection an option and how would i apply it? This is not a unittest/mock scenario, but would PrivateObject fit nevertheless? Dynamic assembly loading?

Totally different approaches welcome!





Aucun commentaire:

Enregistrer un commentaire