Reputation: 203
I'm working with a C# plugin architecture.
Plugins are DLL's which expose a bunch of presenters, which are objects that implement the IPresenter
interface.
The IPresenter
interface is available in a DLL shared by all plugins.
Presenters can also implement additional methods as defined by IAction
interfaces, like ILoadAction
, ISaveAction
, etc.
These interfaces are also shared by the same DLL so all plugins can have presenters that implement such interfaces.
Case: I have presenter X
in plugin A
which implements the IPresenter
interface and the ILoadAction interface.
In plugin B
, I ask the plugin architecture to give me a presenter X
. This gives me an <i>IPresenter</i>
object.
To call the LoadAction method of that presenter, I have to cast the presenter to ILoadAction
.
Problem: if I remove ILoadAction
from presenter X
in plugin A
, the code in plugin B
will still compile even though the presenter doesn't implement ILoadAction
anymore.
In such cases, I'd like to be warned by the compiler.
Actually, I'd like to avoid having to cast to a certain IAction
all the time.
Question: how to deal with that?
Upvotes: 2
Views: 359
Reputation: 71080
I'm afraid that the compiler won't help you here. Plugin A can be changed at any time, before, during or after B is build, so your plugin architecture needs to cope with the possible loss of interfaces - either return null values for the interface or throw an exception.
As for the getting items of the right type, this can be acheived using generics:
T IPresenter.GetAction <T> where T : class, IAction ()
{
return (T) GetAction (typeof T)
}
so the cast is done in the GetAction method rather than the caller (sort of):
var action = PluginA.GetAction <ILoadAction> ();
EDIT:
If doing the <> in the call is too much, try:
bool GetAction<T> (out T a) where T : class, IAction
{
// stuff
return interface_found; // or throw an exception?
}
Then you can do:
ILoadAction action;
if (!PluginA.GetAction (out action))
{
// failed to get interface!
}
Upvotes: 2
Reputation: 3272
Two options:
Upvotes: 0