public
Created

  • Download Gist
ExportFactory.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Linq;
using System.Text;
 
namespace MefDemo
{
class Program
{
static void Main(string[] args)
{
var container = new CompositionContainer(
new AssemblyCatalog(typeof(Program).Assembly)
);
var receiver = container.GetExport<TaskListener>();
 
receiver.Value.Accept();
receiver.Value.Accept();
receiver.Value.Accept();
 
Console.ReadKey();
}
}
 
[Export]
public class TaskListener
{
private readonly ExportFactory<TaskProcessor> taskProcessorFactory;
 
[ImportingConstructor]
public TaskListener(ExportFactory<TaskProcessor> taskProcessorFactory)
{
this.taskProcessorFactory = taskProcessorFactory;
}
 
public void Accept()
{
using (var processor = taskProcessorFactory.CreateExport())
{
processor.Value.Process();
}
}
}
 
[Export]
public class TaskProcessor
{
private readonly DataContext dataContext;
 
[ImportingConstructor]
public TaskProcessor(DataContext dataContext)
{
Console.WriteLine("Ceated");
this.dataContext = dataContext;
}
 
public void Process()
{
Console.WriteLine("Processing...");
}
}
 
[Export]
public class DataContext : IDisposable
{
public DataContext()
{
Console.WriteLine("Data context created");
}
 
public void Dispose()
{
Console.WriteLine("Data context disposed");
}
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.