آموزش MEF#1
نویسنده: مسعود پاکدل
تاریخ: ۱۳۹۱/۱۱/۲۴ ۲۳:۱۵
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
public interface IViewModel
{
string Name { get; set; }
}[Export( typeof( IViewModel ) )]
public class ViewModelFirst : IViewModel
{
public ViewModelFirst()
{
this.Name = "ViewModelFirst";
}
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
private string _name;
}[Export( typeof( IViewModel ) )]
public class ViewModelSecond : IViewModel
{
public ViewModelSecond()
{
this.Name = "ViewModelSecond";
}
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
private string _name;
}public class PluginManager
{
public PluginManager()
{
}
public IList<IViewModel> ViewModels
{
get
{
return _viewModels;
}
private set
{
_viewModels = value;
}
}
[ImportMany( typeof( IViewModel ) )]
private IList<IViewModel> _viewModels = new List<IViewModel>();
public void SetupManager()
{
AggregateCatalog aggregateCatalog = new AggregateCatalog();
CompositionContainer container = new CompositionContainer( aggregateCatalog );
CompositionBatch batch = new CompositionBatch();
batch.AddPart( this );
aggregateCatalog.Catalogs.Add( new AssemblyCatalog( Assembly.GetExecutingAssembly() ) );
container.Compose( batch );
}aggregateCatalog.Catalogs.Add( new AssemblyCatalog( Assembly.GetExecutingAssembly() ) );
static void Main( string[] args )
{
PluginManager plugin = new PluginManager();
Console.WriteLine( string.Format( "Number Of ViewModels Before Plugin Setup Is [ {0} ]", plugin.ViewModels.Count ) );
Console.WriteLine( Environment.NewLine );
plugin.SetupManager();
Console.WriteLine( string.Format( "Number Of ViewModels After Plugin Setup Is [ {0} ]", plugin.ViewModels.Count ) );
Console.ReadLine();
}[Export( "ModuleA" , typeof( IMyInterface) )]
public class ClassA : IMyInterface
{
}
[Export( "ModuleB" , typeof( IMyInterface))]
public class ClassB : IMyInterface
{
} public class ModuleA
{
[ImportingConstructor]
public ModuleA([ImportMany( "ModuleA" , IMyInterface)] IEnumerable<IMyInterface> controllers )
{
}