Restricting who can implement an interface
When designing an interface, it is sometimes preferable to prevent others from implementing it. Indeed, once someone implements the interface, adding new members is no longer possible without breaking any class that implements it.
Metalama provides a way to protect your interface from being implemented by other assemblies. To do this, follow these steps.
Add the
Metalama.Extensions.Architecture
package to your project.Annotate the interface with the InternalOnlyImplementAttribute. This attribute will prevent any other assemblies from implementing your interface.
Example
In the parent project, assume we have the following interface protected by the InternalOnlyImplementAttribute attribute:
using Metalama.Extensions.Architecture.Aspects;
namespace Doc.Architecture.InternalOnlyImplement
{
[InternalOnlyImplement]
public interface IMyInterface { }
}
If we try to implement this interface in a child project, a warning is reported:
1namespace Doc.Architecture.InternalOnlyImplement
2{
Warning LAMA0901: The 'IMyInterface' interface can only be implemented by the 'InternalOnlyImplement` project or from another project having access to its internals.
3 class TheImplementation : IMyInterface { }
4}
5
1namespace Doc.Architecture.InternalOnlyImplement
2{
3 class TheImplementation : IMyInterface { }
4}
5