Print Page | Close Window

MEF Import Property

Printed From: IdeaBlade
Category: Cocktail
Forum Name: Community Forum
Forum Discription: A professional application framework using Caliburn.Micro and DevForce
URL: http://www.ideablade.com/forum/forum_posts.asp?TID=3986
Printed Date: 15-May-2024 at 8:01pm


Topic: MEF Import Property
Posted By: gregweb
Subject: MEF Import Property
Date Posted: 08-Feb-2013 at 10:28am
In the DbIntializer, instead of one large seed method, I have it broken out into different classes one for each type, using an Interface, ISeedDb.

I am then trying to import them through a property on the DbInitializer. However, I no imports come through:

public interface ISeedDatabase {
        bool HasRoot { get; }
        void Seed(JetDbContext context);
    }



public class JetDbInitializer : CreateDatabaseIfNotExists<JetDbContext>
    {
        [ImportMany]
        public IEnumerable<ISeedDatabase> Seeds { get; set; }
}

[Export(typeof(ISeedDatabase)), PartCreationPolicy(CreationPolicy.Shared)]
    public class SeedPhoneTypes : ISeedDatabase
    {
        public bool HasRoot { get { return false; }}
        public void Seed(JetDbContext context) {
            var phoneTypes = new List<PhoneNumberType>
                                 {
                                    new PhoneNumberType {Id = CombGuid.NewGuid(), Name = "Home", Default = true},
                                    new PhoneNumberType {Id = CombGuid.NewGuid(), Name = "Work"},
                                    new PhoneNumberType {Id = CombGuid.NewGuid(), Name = "Mobile"}
                                 };
            phoneTypes.ForEach(e => context.PhoneNumberTypes.Add(e));
        }
    }

I am not sure what I am doing wrong.

Greg



Replies:
Posted By: mgood
Date Posted: 08-Feb-2013 at 11:10am
Greg,
Dependencies are only satisfied if the part in question is managed by MEF. If you simply new up your JetDbInitializer, MEF has no awareness of it and won't satisfy any dependencies. You have two options.
 
First option, you can manually satisfy the dependencies by passing the JetDbInitializer instance to Composition.BuildUp(). For example you can do that in the JetDbInitializer ctor by calling Composition.BuildUp(this).
 
The other option, you export the JetDbInitializer and then create the instance by calling Composition.GetInstance<JetDbInitializer>().
 
[Export, PartCreationPolicy(CreationPolicy.NonShared)]
public class JetDbInitializer : CreateDatabaseIfNotExists<JetDbContext>
{
[ImportMany]
public IEnumerable<ISeedDatabase> Seeds { get; set; }
}


Posted By: gregweb
Date Posted: 08-Feb-2013 at 6:17pm
Thanks, got that working.



Print Page | Close Window