Skip to content

Instantly share code, notes, and snippets.

@XSockets
Last active December 25, 2015 12:59
Show Gist options
  • Save XSockets/6980505 to your computer and use it in GitHub Desktop.
Save XSockets/6980505 to your computer and use it in GitHub Desktop.
XSockets Plugin Framework - Sample 1 - Compose with Attributes
//Code below will output...
/*
Name: Boston Zoo
Animals in Zoo
Type: Lion
Says: My name is gorgeous george
Is Carnivore: True
Type: Horse
Says: Where's my cowboy?
Is Carnivore: False
Hit enter to quit...
*/
//IMPORTANT: The Zoo, Lion and Horse classes is unknown at compile & runtime, so we load them
//We could also have been pointing out a plugincatalog or just dropped the assemblies in the bin folder
Plugin.Framework.Composable.LoadAssembly(
@"PathToAssmeblyWithClassImplementationsOfInterfaces.dll");
//Now when we say get one implementaion of IZoo we will get the class Zoo that we do not know about
//And that class will have a list of IAnimal that is not references either...
var zoo = Plugin.Framework.Composable.GetExport<IZoo>();
Console.WriteLine("Name: {0}", zoo.Name);
Console.WriteLine("Animals in Zoo");
foreach (var animal in zoo.Animals)
{
Console.WriteLine("Type: {0}", animal.GetType().Name);
Console.WriteLine("Says: {0}", animal.Say());
Console.WriteLine("Is Carnivore: {0}", animal.IsCarnivore);
}
Console.WriteLine("Hit enter to quit...");
Console.ReadLine();
//Implement 1 class for IZoo, and 2 classes for IAnimal... Import & Export as needed...
/// <summary>
/// Implement Zoo interface
/// Export the IZoo interface so that the plugin framework knows about it
/// Tell the plugin framework to ImportMany IAnimal
/// </summary>
[Export(typeof(IZoo))]
public class Zoo : IZoo
{
public string Name {
get { return "Boston Zoo"; }
}
[ImportMany(typeof(IAnimal))]
public IList<IAnimal> Animals { get; set; }
}
/// <summary>
/// Implement IAnimal interface on a Lion class
/// Export the IAnimal interface so that the plugin framework knows about it
/// </summary>
[Export(typeof(IAnimal))]
public class Lion : IAnimal
{
public string Say()
{
return "My name is gorgeous george";
}
public bool IsCarnivore
{
get { return true; }
}
}
/// <summary>
/// Implement IAnimal interface on a Horse class
/// Export the IAnimal interface so that the plugin framework knows about it
/// </summary>
[Export(typeof(IAnimal))]
public class Horse : IAnimal
{
public string Say()
{
return "Where's my cowboy?";
}
public bool IsCarnivore
{
get { return false; }
}
}
//Interfaces to Export/Import in the plugin framework
/// <summary>
/// My awesome Zoo, lets fill it with animals!
/// </summary>
public interface IZoo
{
string Name { get; }
IList<IAnimal> Animals { get; set; }
}
/// <summary>
/// Some kind of animal
/// </summary>
public interface IAnimal
{
string Say();
bool IsCarnivore { get; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment