Contents tagged with MEF

  • The Aspen progress – Silverlight 4, Net 4, WCF RIA Services ref. project

    It was a while since I wrote a blog post, the reason are many, first preparation for the SDC2010 conference where I talked about WCF RIA Services, then 2 sessions at Microsoft TechDays 2010 where I talked about Web Form vs MVC and building business application with Silverlight 4, MVVM and WCF RIA Services.. and then bought a new car and also have bean on the Microsoft Visual Studio 2010 Ultimate tour and one week vacation in Italy. So a busy time. This blog post will only mention some of the latest updates we have made to the project.

    Data Model and Domain Model changes

    We still uses POCOs but we have removed the Code First feature because it’s not part of the EF 4.0 RTM. Instead Dag König have added the support of using T4 templates. So we create our entities out from our Data Model by using T4 POCO templates. You can find the template “”  in the project “Fdd.Aspen.DomainModel” and under the folder “Entities”.

    “Defensive programming/argument validations”

    Before we used methods to check if the user of the code passes in a correct value to our methods etc, now we have replaces it with Code Contract. The following is an example where we have for example used Code Contract:

    public BaseRepository(IObjectContext objectContext)
          Contract.Requires(objectContext != null);
          Contract.Ensures(_objectContext != null);
          Contract.Ensures(_objectSet != null);
          _objectContext = objectContext;
          _objectSet = _objectContext.CreateObjectSet<TEntity>();

    First we Requires that the objectContext attribute can’t be null, if it’s not null we will ensure the the private fields _objectContext and _objectSet will not be null. Code Contract is all about setting up a contract “if you give me this, I promise that you will get this.”. So by using pre-condition “Requires” we can check if the user of the code passes in the correct value we expected to get, then we use post-condition “Ensures” to make sure we fulfill our part of the contract. We also use Contract Invariant, to make sure the object is in a good state.

    [ContractInvariantMethod] private void ObjectInvariant() { Contract.Invariant(_objectContext != null); Contract.Invariant(_objectSet != null); }

    We haven’t upgraded all our code to use Code Contract yet,  but while we working with a old class we will do the changes, every new class will use Code Contract.

    ViewModel and the Client Side Data Channel

    At the moment there are no changes made to the client-side and ViewModel. We will not use a 3ed party framework or Prism etc, we will try to use most of the things shipped with the RTM version of Silverlight 4 and VS2010. I haven’t mention anything about the client-side in a blog post yet even if there are some test code added to try out some infrastructure stuffs. To make it easy to do the testing we will work with an abstraction of the server call. At the moment we call it a DataChannel but some people also call it “Repository” for the client-side. The name here is not so important.

    public class ListMemberViewModelDataChannel : IListMemberViewModelDataChannel
        MemberDomainContext _memberDomainContext = new MemberDomainContext();
        public void GetAllMembersAsync(Action<IEnumerable<MemberPM>> getAllMembersCompletedCallBack)
                           loadOperation =>
                           , null);
       public void Save()

    The ListMemberViewModelDataChannel is the “DataChannel” for the ListMemberViewModel, it have the responsibility to handle all communication to the server-layer on the server-side. The DataChannel will use WCF RIA Services, and one DataChannel will be create for one View, and one DomainService will be used for one View. The reason why we use a “DataChannel”, is to make it easy to do testing against our ViewModel and also if we don’t want to use WCF RIA Services, we can simply implement a DataChannel that will use WCF.

    The following is an example of a ViewModel that uses a DataChannel:

    public class ListMemberViewModel : BaseViewModel
        private ObservableCollection<MemberPM> _members = null;
        private IListMemberViewModelDataChannel _listMemberViewService;
        private bool _isBusy = false;
        public ListMemberViewModel(IListMemberViewModelDataChannel listMemberViewService)
             Contract.Requires(listMemberViewService != null);
             Contract.Ensures(_listMemberViewService != null);
             this._listMemberViewService = listMemberViewService;
             this.IsBusy = true;
         private void GetAllMembersCompleted(IEnumerable<MemberPM> result)
             this.Members = new ObservableCollection<MemberPM>(result);
             this.IsBusy = false;
         public bool IsBusy
            get { return _isBusy; }
            private set
               _isBusy = value;
         public ObservableCollection<MemberPM> Members
             get { return _members; }
             private set
                _members = value;

    On the server-side in our DomainServices we don’t expose our DomainModel’s Domain entities, instead we create a “Presentation Model”, a model more suitable for presentation purpose. They will be part of the ViewModel, and thanks to the WCF RIA Services uses of the INotifyDataErrorInfo interface, we can use the “Presentation Model” as part of the ViewModel (it’s a ViewModel more or less in the way it’s implemented but with not operation added to it). We haven’t added the infrastructure for location our ViewModels and bind them to the Views yet, we are thinking about using MEF or Unity 2.0, or maybe combine both of them. At the moment we use simply hardcode the dependencies and do the injection manually in the View’s code-behind:

    public MainPage()
         var listMemberViewModel = new ListMemberViewModel(new ListMemberViewModelDataChannel());
         this.DataContext = listMemberViewModel;

    This will be changed, I’m thinking about using convention to locate the ViewModel for the View.

    If you want to know when I post a new blog post, you can follow me on twitter:


  • Aspen – A sample app using Silverlight 4 and .Net 4.0 – part 2 of X – MEF and EF 4 code-only

    Note: The code examples in this blog post will be based on technical previews and betas of .Net 4.0 and VS2010. So changes can be made before it hits RTM.

    If you haven’t read the first part about the Aspen project, you can find it here.

    In this part I will focus on the Entity Framework 4 CTP2 Code-only feature and the use of POCOs. To import some mapping configuration I have used MEF. I’m only working on the skeleton on the backend at the moment. What I have done so far is adding the first Entity, the Member! We want to use a POCO for the Entity and here is the code for the Member entity. No references to the EF assemblies, no annotations, no inherits or implementation of interfaces, just a plain old CLR object (POCO):

    public class Member
        public int ID { get; internal set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }

    This Entity is far from completed we will add more properties later, but now I wanted to test the new code-only support, so I just added a few properties. The Entity exists in its own Class Library where we will add our Domain Model. I haven’t implemented a Repository for this Entity yet. I will be done when I’m satisfied with the code-only part and helper classes.

    When using POCO we need to create our own ObjectContext. I have created a simple one called AspenObjectContext. This class will later support more entities, but at the moment it will only have one, the Member. Here is the code for the AspenObjectContext:

    public class AspenObjectContext : ObjectContext
        public AspenObjectContext(EntityConnection conn) : base(conn) { }
        public ObjectSet<Member> Members
                return base.CreateObjectSet<Member>();

    To create an ObjectContext we need to inherit the ObjectContext class from the System.Data.Objects namespace (System.Data.Entity.dll). The constructor will take an EntityConnection and also have a getter for accessing the ObjectSet of the Member entity. The AspenObjectContext is located in its own Class Library, at the moment together with the Repositories for the entities (which is not created yet ;)). I will see if I will keep the AspenObjectContext in the same assembly as the Repositories. The reason why I have placed it with the Repositories now is because they are going to use the AspenObjectContext. I will see if I will try to follow the Dependency Inversion Principle here, so the Repositories will not be dependent on the AspenObjectContext, instead of an abstraction (interface). In this case the app will only use Entity Framework 4 and that will not be changed. You can of course send me comments about what you would prefer etc.

    When using POCO we can use a EDMX for the mapping, but I decided to use the new code-only feature. When using the code-only feature we can for example create an EntityConfiguration class for the Entity, where a fluent-API can be used to configure the mapping between the database and the entity. Here is the mapping class for the Member entity:

    class MemberMappingConfiguration : EntityConfiguration<Member>
        public MemberMappingConfiguration()
             base.Property(m => m.ID).IsIdentity();
                     m =>
                         ID = m.ID,
                         FirstName = m.FirstName,
                         LastName = m.LastName

    By using the Property method of the EntityConfiguration class we can for example specify if a specific property should be the identifier. In this case the ID property of the Member entity. The MapSingleType is used to map the database columns (first property in the anonymous type) to the Member’s properties. The ToTable will tell which table the Member entity should map against, in this case the Members table.


    Note: I often create the Domain Model first and test it before I focus on the database. But in this case I needed to test the code-only feature, so I created the database and added a table with the name Members. I’m thinking of renaming the table to Member instead. What is your comments on the naming of tables?

    The EntityConfiguration must be registered somehow so the AspenObjectContext can use the code-only mapping. This is done by using the ContextBuilder class and it’s Configurations property. In the future there will be several of EntiyConfiguration classes for each Entity, so I decided to use MEF to import the configurations. That is the reason why the [Export(typeof(StructuralTypeConfiguration))] is added to the MemberMappingConfiguration class. The configuration classes are added to their own class library. I want to use MEF to separate the configuration from the AspenObjectContext assembly. This is the part I would really like to have some comments on, how should you have done it etc. I decided to create a AspenObjectContextFactory class to create the AspenObjectContext instance and also use the ContextBuilder to configure the ObjectContext and the mappings. Here is the code of the AspenObjectContextFactory and where MEF is used to import the EntityConfiguration classes:

    public class AspenObjectContextFactory
        [ImportMany(typeof(StructuralTypeConfiguration), AllowRecomposition=true)]
        private List<StructuralTypeConfiguration> _configurations = null;
         public AspenObjectContext Create(DbConnection con)
             if (_configurations == null)
             var builder = new ContextBuilder<AspenObjectContext>();
             if (_configurations != null)
                 _configurations.ForEach(c => builder.Configurations.Add(c));
             return builder.Create(con);

    void Compose() { var assemblies = AppDomain.CurrentDomain.GetAssemblies(); var catalogParts = new AggregateCatalog(); foreach (var assembly in assemblies) { if (assembly.FullName.Contains("EntityMapping")) catalogParts.Catalogs.Add( new AssemblyCatalog(assembly)); } var container = new CompositionContainer(catalogParts); container.ComposeParts(this); } } }

    The ContextBuilder’s Create method will create the AspenObjectContext, and the method needs a connection so the DbConnection base class is used as the type of the Create method’s argument. I’m planning to use Untiy as the IoC Container to inject dependencies (or maybe stay with MEF only), but aren’t there yet. The _configurations List has the MEF’s ImportMany attribute to imports the EntityConfiguration classes. The reason I use the StructuralTypeConfiguration as the contract for the Import and Export, is because I don’t want to use a string, and the EntityConfiguration is a generic class. The EntityConfiguration inherits from the StructuralTypeConfiguration class and the ContextBuilder’s Configurations’s Add method takes a StructuralTypeConfiguration (The Add method is used to add the configuraitons to the ContextBuilder).

    The Compose method will only be called when the _configuration is null for doing the composition. The Compose method will get all assemblies loaded to the AppDomain and will only add the Assemblies with the name “EntityMapping“. In this case I wanted to avoid configuration so I decided to use convention. I could just Load the assembly with the EntityConfigurations, but I decided to locate it without any specific configurations (In this case a referenced is needed. But I could have used configuration. Instead just specify the path to the mapping configuration assembly in a config file. By doing so I could easily replace the assembly and no reference is needed). I can now add other assemblies with the name EntityMapping, which can have some new mappings against new entities  etc. I would really like to have some comments on this solution also´, and have in mind this is still under development and changes can be made to the code. I only put something together for trying the code-only feature.

    Here is the code for using the AspenObjectContext (The code will only insert new Members):

    var aspenContext = new AspenObjectContextFactory().Create(
    aspenContext.Members.AddObject(new Member() { FirstName = "John", LastName = "Doe" });

    If you have any comments on this first part and also want to see some specific feature, please let me know. I would be glad if you can come with some suggestions.

    If you want to know when I publish more posts about this app and the progress, you can follow me on twitter:


  • Aspen – A sample app using Silverlight 4 and .Net 4.0 – part 1 of X

    Together with Dag König and Danwei Tran at Microsoft, I’m building an app with the code name “Aspen”. This application will use most of the new features shipped with Visual Studio 2010, such as, Silverlight 4, Entity Framework 4, MEF, WCF RIA Services etc. We are going to use the MVVM pattern and a sort of Domain Driven Design (DDD) approach. Danwei is the GUI designer, she will use Sketchflow and Expression Blend 4. Dag König is the “Standards authority” and  will also do some development. My part is to be a developer, both backend and client-side. I will blog about our progress on my blog and that is the reason for the X in the title of this blog post. I don’t know how many parts it will be ;)