Search code examples
c#interfaceapi-design

C# Interface that needs to be implemented by a third-party


I'm developing an API for third-party users and I'm stuck:

The API will look like the following:

public interface IFoo
{
    Init(IComponent component);

    ...
}

The interface needs to be implemented by the third-party, but the Init method will be called by us. My problem is that I will pass an IComponent instance to them, which they can use in the Init method, but they should not use anywhere else.

Is it possible to do such a runtime check that they did not save it, or organize this kind of behaviour somehow that will make it impossible to use that IComponent instance out of the Init method?


Solution

  • I do not think you can directly control how Init() is implemented anywhere. However, your IComponent can be as sneaky as it needs to be, doing something like the code below will make it impossible for plugins to use the instance after the fact.

    public interface IComponent
    {
        void DoSomething();
    }
    
    class Component : IComponent
    {
        bool flag;
    
        public DoSomething()
        {
            if( flag )
                throw new NotSupportedException( "Operation not supported anymore." );
            // Do something normal during Init().
        }
    
        internal void MarkCOmplete()
        {
            flag = true;
        }
    }
    
    ....
    
    void Initialize()
    {
        var component = new Component();
    
        foreach(var plugin in plugins)
        {
            plugin.Init(component);
        }
        component.MarkComplete();
    }