CodePaste Logo
New Snippet New Snippet Recent Snippets Recent Snippets My Snippets My Snippets Web Code Search Snippets Search
Sign inor Register
Language: C#

Using ConvensionPart<T> to compose using conventions

340 Views
Copy Code Show/Hide Line Numbers
public class ConventionPart<T> : IPartImportsSatisfiedNotification
{
    /// <summary>
    /// Initializes a new instance of the <see cref="ConventionPart{T}"/> class.
    /// </summary>
    public ConventionPart()
    {
    }
 
    [ImportMany]
    public T[] Import { get; set; }
 
    /// <summary>
    /// Gets or sets a value indicating whether this instance has been satisfied.
    /// </summary>
    /// <value><see langword="true"/> if this instance has been satisfied; otherwise, <see langword="false"/>.</value>
    public bool HasBeenSatisfied { get; private set; }
 
    /// <summary>
    /// Called when <see cref="Import"/> has been satisfied.
    /// </summary>
    public void OnImportsSatisfied()
    {
        this.HasBeenSatisfied = true;
    }
}
 
public class ConventionPartTest
{
    [Fact]
    public void Import_should_be_satisfied_by_container()
    {
        var part =
            new ConventionPart<ILogger>();
 
        var typeLoader =
            new TypeLoader();
 
        typeLoader.AddTypes(() =>
            Assembly.GetExecutingAssembly().GetExportedTypes());
 
        var catalog =
            new ConventionsCatalog(new[] { new LoggerRegistry() }, typeLoader);
 
        var batch =
            new CompositionBatch();
        batch.AddPart(part);
 
        var container =
            new CompositionContainer(catalog);
        container.Compose(batch);
 
        Assert.Equal(1, part.Import.Count());
    }
}
 
public class LoggerRegistry : PartRegistry
{
    public LoggerRegistry()
    {
        Part<PartConvention>()
            .ForTypesMatching(x => x.GetInterfaces().Contains(typeof(ILogger)))
            .Exports(x => x.Export<ExportConvention>().Members(m => new[] { m }));
    }
}
 
public interface ILogger
{
    void Add(string message);
}
 
public class NullLogger : ILogger
{
    public void Add(string message)
    {
    }
}
by TheCodeJunkie
  February 07, 2010 @ 3:14pm
Tags:

Add a comment


Report Abuse
brought to you by:
West Wind Techologies



If you find this site useful and use it frequently please consider making a donation to support this free service.
Donate