Skip to content

Instantly share code, notes, and snippets.

@ArseniySavin
Created March 13, 2017 02:39
Show Gist options
  • Save ArseniySavin/637da7ca83b5c3199db0cfed3be7d8e1 to your computer and use it in GitHub Desktop.
Save ArseniySavin/637da7ca83b5c3199db0cfed3be7d8e1 to your computer and use it in GitHub Desktop.
MEF Example
#region MEF dll example
namespace MEF
{
public interface ICore
{
String PerformOperations(string data, string command);
string Operation(string data, IOperation oper);
}
[Export(typeof(MEF.ICore))]
public class Core : ICore
{
[ImportMany]
private IEnumerable<Lazy<IOperation, IOperationCommand>> _operations;
public string Operation(string data, IOperation oper)
{
return oper.Operate(data);
}
public string PerformOperations(string data, string command)
{
foreach (Lazy<IOperation, IOperationCommand> i in _operations)
{
if (i.Metadata.Command.Equals(command))
return i.Value.Operate(data);
}
return "Unrecognized operation";
}
}
public interface IOperation
{
string Operate(string data);
}
public interface IOperationCommand
{
String Command { get; }
}
[Export(typeof(MEF.IOperation))]
[ExportMetadata("Command", "upper")]
public class UpperCase : IOperation
{
public string Operate(string data)
{
return data.ToUpper();
}
}
[Export(typeof(MEF.IOperation))]
[ExportMetadata("Command", "lower")]
public class LowerCase : IOperation
{
public string Operate(string data)
{
return data.ToLower();
}
}
[Export(typeof(MEF.IOperation))]
[ExportMetadata("Command", "reverse")]
public class Reverse : IOperation
{
public string Operate(string data)
{
return new string(data.ToCharArray().Reverse().ToArray());
}
}
[Export(typeof(MEF.IOperation))]
[ExportMetadata("Command", "new")]
public class NewString : IOperation
{
public string Operate(string data)
{
return "Привет MEF!!!";
}
}
}
#endregion
#region DEMO
class Program
{
private CompositionContainer _compositionContainer;
[Import(typeof(MEF.ICore))]
public ICore core;
private Program()
{
var agregateCatalog = new AggregateCatalog();
//agregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof(Program).Assembly));
agregateCatalog.Catalogs.Add(new DirectoryCatalog("Extensions"));
_compositionContainer = new CompositionContainer(agregateCatalog);
try
{
this._compositionContainer.ComposeParts(this);
}
catch (CompositionException compositionException)
{
Console.WriteLine(compositionException.ToString());
}
}
static void Main(string[] args)
{
Program program = new Program();
string data, command;
while (true)
{
Console.Clear();
data = "test";
command = "upper";
Console.Write("Result: " + program.core.PerformOperations(data, command));
//Console.Write("Result: " + program.core.Operation(data, new UpperCase()));
Console.ReadLine();
}
}
}
#endregion
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment