I have the following in assembly C :
public interface InterfaceA
{
string Data {get; }
}
public interface InterfaceB
{
InterfaceA DoStuff();
}
public interface InterfaceC
{
IEnumerable<InterfaceA> GetStuffThatHaveBeenDone();
}
An implementation of InterfaceB is, called Doer is defined in the Assembly A (which is the main project). Similarly an implementation of the InterfaceA is defined in AssemblyA, but the assembly B knows nothing about these implementations.
The assembly B will be developped by an external company, and will be referenced by assembly A (not dynamically, at design time). The purpose of this company is to write an implementation for InterfaceC.
Here is the situation : I want to prevent the external company from creating its own implementation of InterfaceA and putting it in the list they return in InterfaceC.GetStuffThatHaveBeenDone(). The intended usage is : they call InterfaceB.DoStuff(), get an instance of InterfaceA, and add it to the list that they will return.
I have to make an assumption on the type of the objects contained in the list returned by InterfaceC.GetStuffThatHaveBeenDone(). I know they will all have a certain type that is only defined in assembly A. Therefore I'm trying to make sure that these objects will only be created in assembly A, and I want to enforce this at compile time to avoid discovering MyCustomImplementionOfA objects in the list.
Therefore I'm trying to figure out how to prevent an interface from being implemented in another assembly. I'm thinking that perhaps there can be a way around it by slightly rethinking my design buy I don't seem to find one.
Thank you
I like the solution with the opaque token proposed by Eric.
You can also pull this trick by using an abstract class in place of your InterfaceA and making its constructor internal.
public abstract class ContractA
{
internal ContractA() {};
public abstract string Data {get; }
}
The only way I can think of to do this is to create an opaque object which you pass back to them:
internal interface InterfaceA
{
string Data {get; }
}
public interface InterfaceB
{
OpaqueToken DoStuff();
}
public interface InterfaceC
{
IEnumerable<OpaqueToken> GetStuffThatHaveBeenDone();
}
public sealed class OpaqueToken
{
internal OpaqueToken() {}
internal InterfaceA A { get; set; }
}
This way InterfaceA is internal, so only code within your library (unless you use InternalsVisibleTo) will be able to implement it. The consumer of your library will only see instances of OpaqueToken and your constructor is internal so they won't be able to invoke it. The object which implements InterfaceA will only be accessible within your library as well. OpaqueToken could even implement InterfaceA if you like.
It's important to point out that this is not a security measure -- any consumer using reflection can violate all these rules.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With