
Import
You can get the exported modules in several ways:
- Use methods
GetExport<T>andGetExports<T> - Use the
ImportOneandImportManyattribute - Use the
ImportingConstructorattribute
Obviously the GetExport and ImportOne will return a single instance while the GetExports and ImportMany will return a list of exported instances.
GetExport
You have seen this previously in the documentation, for example when we use the IXLogger module.
To get an instance of our IAwesome module we just use
var awesome = Composable.GetExport<IAwesome>();
Now that we have the instance we can call the method declared on the IAwesome interface
awesome.DoStuff();
GetExports
Returns a list of T instead of a single instance. This is for example used in XSockets for protocols and controllers that is multiple exports of IXSocketProtocol and IXSocketController
Since we only have one IAwesome module this will only return a list with one item.
foreach (var m in Composable.GetExports<IAwesome>())
m.DoStuff();
ImportOne / Importmany
Decorate properties on a Exported interface with this attribute and the PluginFramework will create instances for the property/properties when the composition in done.
Note if you are using ImportMany the attribute usage should say:
[ImportMany(typeof(IList<IB>))]
Example
Interfaces
We have 2 interfaces (IA and IB). Both interfaces are exported. IA imports IB as a property and IB has a method called Square
[Export(typeof(IA))]
public interface IA
{
[ImportOne(typeof(IB))]
IB B { get; set; }
}
[Export(typeof(IB))]
public interface IB
{
void Square(int i);
}
Classes
All we need to do to make this work is to implement the interfaces. So lets create the classes A and B. Notice that we do not need any attributes or usings specific for the PluginFramework, so the implementations could have been in a separate assembly unknown at compile-time.
public class A : IA
{
public IB B { get; set; }
}
public class B : IB
{
public void Square(int i)
{
Console.WriteLine(i * i);
}
}
Test
//Will output 4 into the console
Composable.GetExport<IA>().B.Square(2);
ImportingConstructor
Decorate the ctor on a Exported type with this attribute and the PluginFramework will inject the modules as parameters when the composition in done.
Example
Interfaces
We have 2 interfaces (IA and IB). Both interfaces are exported. IA imports IB as a property and IB has a method called Square
[Export(typeof(IA))]
public interface IA
{
IB B { get; set; }
}
[Export(typeof(IB))]
public interface IB
{
void Square(int i);
}
Classes
Notice that since interfaces cant have constructors defined we have to add the attribute in the implementation.
public class A : IA
{
public IB B { get; set; }
[ImportingConstructor]
public A(IB b)
{
this.B = b;
}
}
public class B : IB
{
public void Square(int i)
{
Console.WriteLine(i * i);
}
}
Test
//Will output 4 into the console
Composable.GetExport<IA>().B.Square(2);