Use StructureMap and Castle DynamicProxy to easily change the semantics of your code

In this posting my intentions are to show you how to use Inversion of Control (IoC), with the help of StructureMap, for being able to easily switch the semantics of e.g entities in a model with the change of a few lines in the StructureMap configuration. I will use it to go from plain classes to dynamically generated proxies, using Castle DynamicProxy. The proxied version will add the attributes: Serializable and DataContract. I will not implement any interception, but I will setup a empty interceptor which, if you want, you can extend and play with for yourself.

Ok, even if this might not be the most useful scenario (as it was something I fiddled around with) it shows you how easily it is to control your dependencies(when the infrastructure code is in place). E.g. Lets say that I’m using Entity framework 4 (EF4) and the new capabilities of Code-only and POCO entities and I let EF4 generate proxies to keep track of changes etc. I could then instruct StructureMap to let EF4 create the instances for me at all time and not just when I fetch allready persisted entities.

The solution – Pls.ProxyLab

Pls.Core

Contains some simple “reusable” infrastructure code that could be references by all other assemblies.

Pls.ProxyLab.Client

Simple Console application that consumes and outouts some metadata information about the entities.

Pls.ProxyLab.Entities

Contains the entities of the model

Pls.ProxyLab.IoC

Contains the StructureMap-based IoC-container.

Pls.ProxyLab.IoC.Configuration

Contains the congifurations for the StructureMap-based IoC-container. In this demo I have also put the configuration of the ProxyBuilder in this assembly.

The model

To keep things simple I have not included anything else than simple automatic properties and constructors in my entities.

The entity model of the Pls.ProxyLab

A little note about the constructors. As you will se they are only used for initialization of default values and for resolving dependencies between entities. With the use of StructureMap, I actually wouldn’t need the resolving of the other entities, since I could let StructureMap handle this by autowiring dependencies using property setter injection. The reason to why I’m resolving it in the model is that: It shows the intent more clearly and I also couldn’t get StructureMap to handle the dependencies when I was generating proxies.

All members are made virtual so that Castle DynamicProxy can create proxies and intercept the members.

Entity

A simple base class that (when I start incorporating persistancy) will contain implementation for Identity and Concurrency tokens etc. As of right now it’s an empty shell.

public abstract class Entity
{
}

Person, Customer and Room

Simple classes that extends the Entity baseclass with some automatic properties.

public class Person
    : Entity
{
    public virtual string Firstname { get; set; }
    public virtual string Lastname { get; set; }
}
public class Customer
    : Person
{
    public virtual string CustomerNo { get; set; }
}
public class Room
    : Entity
{
    public virtual string RoomNo { get; set; }
}

BookingRequest

Just a little bit more complicated, as it set’s some default values for its members.

public class BookingRequest
    : Entity
{
    public virtual int NoOfAdultBeds { get; set; }
    public virtual int NoOfChildBeds { get; set; }
    public virtual bool SmokingAllowed { get; set; }
    public virtual bool WantsWindow { get; set; }

    public BookingRequest()
    {
        NoOfAdultBeds = 2;
        NoOfChildBeds = 0;
        SmokingAllowed = false;
        WantsWindow = true;
    }
}

Booking

Not so complicated. The only thing that is new is that is resolves some dependencies to other entities.

public class Booking
    : Entity
{
    public virtual BookingRequest Request { get; set; }
    public virtual string BookingNo { get; set; }
    public virtual Customer Customer { get; set; }
    public virtual Room Room { get; set; }

    public Booking()
    {
        Request = EntityFactory.Instance.GetInstance<BookingRequest>();
        Customer = EntityFactory.Instance.GetInstance<Customer>();
        Room = EntityFactory.Instance.GetInstance<Room>();
    }
}

EntityFactory

I have choosen not to talk directly to my IoC-container, but via a simple singleton based EntityFactory, which in turn communicates with the IoC-Container (ProxyLabObjectContainer). I think it gives a more clean naming and understanding of what’s actually being resolved, and I can add a generic constraint so that only entities can be resolved.

public class EntityFactory
{
    public static EntityFactory Instance
    {
        get { return Singleton<EntityFactory>.Instance; }
    }

    public virtual T GetInstance<T>()
        where T : Entity
    {
        return ProxyLabObjectContainer.Instance.GetInstance<T>();
    }
}

Consuming the model

The code for consuming the model is as simple as:

var booking = EntityFactory.Instance.GetInstance<Booking>();

booking.Customer.Firstname = "Daniel";
booking.Customer.Lastname = "Wertheim";
booking.Request.NoOfAdultBeds = 1;
booking.Request.WantsWindow = false;

The StructureMap based IoC-container

The EntityFactory consumed something called ProxyLabObjectContainer which is an IoC-container that uses StructureMap for resolving the objects. The project (Pls.ProxyLab.IoC) only contains one class, the IoC-container, which extends a baseclass from Pls.Core. The only thing it does is to tell StructureMap to look for configurations (in the form of specific StructureMap Registry implementations) in the assembly Pls.ProxyLab.IoC.Configuration, or rather the assemblyname of the assembly containing the IoC-container + .Configurations.

Configuring the IoC-container – Step 1

public class ProxyLabObjectContainer
    : StructureMapObjectContainer
{
    private static string _configurationNamespace 
        = typeof (ProxyLabObjectContainer).Namespace + ".Configuration";

    public static IObjectContainer Instance
    {
        get
        {
            return Singleton<ProxyLabObjectContainer>.Instance;
        }
    }

    protected override void BootstrapContainer()
    {
        Container.Configure(x => x
            .Scan(scanner =>
                      {
                          scanner.Assembly(_configurationNamespace);
                          scanner.LookForRegistries();
                      })
            );
    }
}

Configuring the IoC-container – Step 2

Create a StructureMap Registry implementation that tells the IoC-container how-to resolve the entities. I do this by telling it to scan a specific assembly for all types that extends Entity. I also explicitly exclude the type Entity, since it is abstract and shall not be resolved.

[Serializable]
public class IoCRegistry
    : Registry
{
    public IoCRegistry()
    {
        Scan(s =>
                {
                    s.AssemblyContainingType<Entity>();
                    s.AddAllTypesOf<Entity>();
                    s.ExcludeType<Entity>();
                });
    }
}

Take it for a testride

If we run the application now (which will output information to the console about extended baseclasses, implemented interfaces and attributes) it will not output that much. No interfaces and no attributes, just the baseclass Entity and ultimately System.Object.

Start using proxies instead

Ok, lets pretend I want to use my entities in a WCF scenario, and I want to implement the attributes: Serializable and DataContract. Instead of adding this manually to my classes I will generate proxies for the classes and inject these attributes.

To get acquainted with Castles DynamicProxy (CDP) I have built my own custom API that wraps the funtionality of CDP. All that code is placed in the Pls.Core assembly. I have an interface that defines my custom IProxyBuilder.

ProxyBuilder

public interface IProxyBuilder
{
    IProxyConfig Config { get; set; }

    object ProxyFromClass(Type proxiedClassType, params IInterceptor[] interceptors);

    T ProxyFromClass<T>(params IInterceptor[] interceptors)
        where T : class;

    object ProxyFromInterface(Type proxiedInterfaceType, params IInterceptor[] interceptors);

    T ProxyFromInterface<T>(params IInterceptor[] interceptors)
        where T : class;
}

The intentions are quite clear: A proxybuilder can create proxies using either classes or interfaces as templates. Either using generics or by passing Types. This is only a fraction of all the overloads and possibilities that Castles DynamicProxy (CDP) offers, so my wrapping interface also gives me a cleaner API and therefore, hopefully, offers less confusions.

The implementation that’s included in Pls.Core is really simple and just forwards the calls to CDP’s ProxyGenerator.

public class ProxyBuilder
    : IProxyBuilder
{
    protected virtual ProxyGenerator ProxyGenerator { get; set; }
    public virtual IProxyConfig Config { get; set;}

    public ProxyBuilder(IProxyConfig config)
    {
        ProxyGenerator = new ProxyGenerator();
        Config = config;
    }

    public virtual object ProxyFromClass(Type proxiedClassType, params IInterceptor[] interceptors)
    {
        return ProxyGenerator.CreateClassProxy(
            proxiedClassType, Config.GenerationOptions, interceptors);
    }

    public virtual T ProxyFromClass<T>(params IInterceptor[] interceptors)
        where T : class
    {
        return ProxyGenerator.CreateClassProxy<T>(
            Config.GenerationOptions, interceptors);
    }

    public virtual object ProxyFromInterface(Type proxiedInterfaceType, params IInterceptor[] interceptors)
    {
        return ProxyGenerator.CreateInterfaceProxyWithoutTarget(
            proxiedInterfaceType, Config.GenerationOptions, interceptors);
    }

    public virtual T ProxyFromInterface<T>(params IInterceptor[] interceptors)
        where T : class
    {
        return ProxyGenerator.CreateInterfaceProxyWithoutTarget<T>(
            Config.GenerationOptions, interceptors);
    }
}

Default ProxyConfig

The ProxyBuilder needs some configuration which is provided by injecting an implementation of my custom IProxyConfig interface. I have made a simple default implementation that I will extend when I setup the configurations to use when creating proxies for my entities.

[Serializable]
public class ProxyConfig
    : IProxyConfig
{
    public virtual ProxyGenerationOptions GenerationOptions { get; private set; }

    public ProxyConfig()
    {
        GenerationOptions = new ProxyGenerationOptions();
    }
}

The EntityProxyConfig

The next step is to create a custom ProxyConfig that I will use to instruct an instance of ProxyBuilder, how-to construct proxies for my entities.

    Instructions:

  • Add Serializable attribute
  • Add DataContract attribute

To achieve this I need to create instances of System.Reflection.Emit.CustomAttributeBuilder and inject them to Castles DynamicProxy’s GenerationOptions.

Serializable – CustomAttributeBuilder

Since this attribute doesn’t have any properties or arguments to provide values for, the cTor overload I need to use is:

public CustomAttributeBuilder(
    System.Reflection.ConstructorInfo con,
    object[] constructorArgs)

Which is done in CreateSerializableAttributeBuilder in EntityProxyConfig.

protected virtual CustomAttributeBuilder CreateSerializableAttributeBuilder()
{
    var attributeType = typeof(SerializableAttribute);
    var ctor = attributeType.GetDefaultCtor();

    return new CustomAttributeBuilder(ctor, new object[0]);
}

The GetDefaultCtor is an extensionmethod that you will find in Pls.Core.

DataContract – CustomAttributeBuilder

This attribute has some properties that I want to pass values to, so I need to use another overload of the cTor of CustomAttributeBuilder:

public CustomAttributeBuilder(
    System.Reflection.ConstructorInfo con,
    object[] constructorArgs,
    System.Reflection.PropertyInfo[] namedProperties,
    object[] propertyValues)

So I need to extract PropertyInfos for the properties I want to set values for (namedProperties) and I need to provide values for them (propertyValues).

protected virtual CustomAttributeBuilder CreateDataContractAttributeBuilder()
{
    var attributeType = typeof(DataContractAttribute);
    var ctor = attributeType.GetDefaultCtor();
    var props = GetPropertiesAndValues(attributeType,
                              new Tuple<string, object>(
                                  "IsReference", DataContractTemplate.IsReference),
                              new Tuple<string, object>(
                                  "Namespace", DataContractTemplate.Namespace));

    return new CustomAttributeBuilder(
        ctor, new object[0],
        props.Select(p => p.Item1).ToArray(),
        props.Select(p => p.Item2).ToArray());
}
protected virtual IEnumerable<Tuple<PropertyInfo, object>> GetPropertiesAndValues(
    Type type, params Tuple<string, object>[] nameValues)
{
    return nameValues.Select(
        nameValue => new Tuple<PropertyInfo, object>(
            type.GetProperty(nameValue.Item1), nameValue.Item2)).ToList();
}

A short explanation. I pass simple Tuples with the name of the property I want and the value I want to provide for it:

  • new Tuple(“IsReference”, DataContractTemplate.IsReference)
  • new Tuple(“Namespace”, DataContractTemplate.Namespace)

So I’m obviously interested in specifying two properties: IsReference and Namespace.

I pass these tuples to a simple helper: GetPropertiesAndValues which returns Tuples where the name of the property is replaced with a PropertyInfo. Hence you will get back:

  • Tuple(xxx, true)
  • Tuple(xxx, “MyNamespace.Org”)

Ok, so where does the values “true” and “MyNamespace.Org” comefrom. The being able to affect the configuration I have provided some properties of the EntityProxyConfig. One property is the “DataContractTemplate” which is an simple instance of the DataContractAttribute. I have also provided some other properties that can be configured. The values are now sat in the cTor which probably would lie somewhere else, but this is just a demo so…

public virtual bool ApplySerializable { get; set; }
public virtual bool ApplyDataContract { get; set; }
public virtual DataContractAttribute DataContractTemplate { get; set; }

public EntityProxyConfig()
{
    ApplySerializable = true;
    ApplyDataContract = true;
    DataContractTemplate = new DataContractAttribute { IsReference = true, Namespace = "MyNamespace.org" };

    InitializeProxyGenerationOptions();
}

That is the important code of the EntityProxyConfig-class, the rest is just code that forms a process (chain of method calls and simple instructions) to initialize the GenerationOptions. To complete code for the class looks like this:

[Serializable]
internal class EntityProxyConfig
    : ProxyConfig
{
    public virtual bool ApplySerializable { get; set; }
    public virtual bool ApplyDataContract { get; set; }
    public virtual DataContractAttribute DataContractTemplate { get; set; }

    public EntityProxyConfig()
    {
        ApplySerializable = true;
        ApplyDataContract = true;
        DataContractTemplate = new DataContractAttribute { IsReference = true, Namespace = "MyNamespace.org" };

        InitializeProxyGenerationOptions();
    }

    protected virtual void InitializeProxyGenerationOptions()
    {
        var attributeBuilders = CreateAttributeBuilders();

        foreach (var attributeBuilder in attributeBuilders)
            GenerationOptions.AdditionalAttributes.Add(attributeBuilder);
    }

    protected virtual IEnumerable<CustomAttributeBuilder> CreateAttributeBuilders()
    {
        return new[] { CreateSerializableAttributeBuilder(), CreateDataContractAttributeBuilder() };
    }

    protected virtual CustomAttributeBuilder CreateSerializableAttributeBuilder()
    {
        var attributeType = typeof(SerializableAttribute);
        var ctor = attributeType.GetDefaultCtor();

        return new CustomAttributeBuilder(ctor, new object[0]);
    }

    protected virtual CustomAttributeBuilder CreateDataContractAttributeBuilder()
    {
        var attributeType = typeof(DataContractAttribute);
        var ctor = attributeType.GetDefaultCtor();
        var props = GetPropertiesAndValues(attributeType,
                                  new Tuple<string, object>(
                                      "IsReference", DataContractTemplate.IsReference),
                                  new Tuple<string, object>(
                                      "Namespace", DataContractTemplate.Namespace));

        return new CustomAttributeBuilder(
            ctor, new object[0],
            props.Select(p => p.Item1).ToArray(),
            props.Select(p => p.Item2).ToArray());
    }

    protected virtual IEnumerable<Tuple<PropertyInfo, object>> GetPropertiesAndValues(
        Type type, params Tuple<string, object>[] nameValues)
    {
        return nameValues.Select(
            nameValue => new Tuple<PropertyInfo, object>(
                type.GetProperty(nameValue.Item1), nameValue.Item2)).ToList();
    }
}

Configure StructureMap to use the ProxyBuilder

If I would like to consume the ProxyBuilder without using StructureMap I would use it like this:

var proxyBuilder = new ProxyBuilder(new EntityProxyConfig());
var bookingItem = proxyBuilder.ProxyFromClass<Booking>(new EntityInterceptor());

I will then get a proxied version of my Booking entity and all calls to its virtual members will be intercepted in my custom EntityInterceptor (more about this later).

Remember the IoCRegistry class that scanned the Pls.ProxyLab.Entities assembly for Entity-implementations? We need to add one single line to it, so that we don’t use StructureMaps default convention, but instead our custom EntityConvention, which in turn will specify that the ProxyBuilder should be used.

The line to be added is:

s.Convention<EntityConvention>();

I will also let the IoC-container be responsible of creating my IProxyBuilder implementation as a Singleton:

For<IProxyBuilder>()
    .LifecycleIs(Lifecycles.GetLifecycle(InstanceScope.Singleton))
    .Use<ProxyBuilder>()
    .Named("EntityProxyBuilder")
    .Ctor<IProxyConfig>().Is<EntityProxyConfig>();

So the complete code now looks like this:

[Serializable]
public class IoCRegistry
    : Registry
{
    public IoCRegistry()
    {
        //Add proxybuilder that are used for creation of my entities
        For<IProxyBuilder>()
            .LifecycleIs(Lifecycles.GetLifecycle(InstanceScope.Singleton))
            .Use<ProxyBuilder>()
            .Named("EntityProxyBuilder")
            .Ctor<IProxyConfig>().Is<EntityProxyConfig>();

        //Add all entities
        Scan(s =>
                {
                    s.Convention<EntityConvention>();
                    s.AssemblyContainingType<Entity>();
                    s.AddAllTypesOf<Entity>();
                    s.ExcludeType<Entity>();
                });
    }
}

EntityConvention

Only one thing left to implement, the EntityConvention that will be used to register all the found Entity implementations.

[Serializable]
internal class EntityConvention
    : IRegistrationConvention
{
    public void Process(Type type, Registry registry)
    {
        registry.For(type).Use(
            ctx =>
            {
                var proxyBuilder = ctx.GetInstance<IProxyBuilder>("EntityProxyBuilder");

                return proxyBuilder.ProxyFromClass(type, new EntityInterceptor());
            });
    }
}

I simply use the previously registrered IProxyBuilder for entities and uses it to create a proxied representation of the specific Entity implementation. I provide my custom EntityInterceptor so that I can intercept interactions made to the virtual members of my entities.

The interceptor is currently empty and just lets all calls pass through.

[Serializable]
internal class EntityInterceptor 
    : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        invocation.Proceed();
    }
}

Take it for a testride

Ok, this time the IoC-container will return proxied entities, hence we will get another output.

Proxied entities

As you can see we are now getting proxies of our entities and they have all gained the injected attributes.

That’s it for now. As always you can download the complete code here.

//Daniel

Putting Entity framework 4 to use in a business architecture

Updates have been made since version 1 of this article!

“>Read more about it here.

Finally I’m finished. I have been struggling with an intended sum-up of my latest post using Entity framework 4. It ended up with an document of about 40 pages. There is a lot of code in there so the number of pages could be a bit missleading (which of course depends on what you are seeking).

Download the pdf

The complete code example can be found here.

As always….. Have fun with it!

//Daniel

Entity framework 4 – Part 5 – Validation using Data Annotations

This post is part of a series of post where I cover different aspects of the new version of Entity framework and the CTP features. I do focus on creating a POCO solutions, hence I don’t use the designer to generate my model.

Part 1 – Getting started
Part 2 – Relationships between non public members
Part 3 – Adding pluralization support to a non strongly typed ObjectContext.
Part 4 – Autoregister Entitymappings

Download the code.

This time I will look at validation using the “System.ComponentModel.DataAnnotations” lib. NOTE! That it doesn’t say “System.Data.Entity.DataAnnotations” or any other specific part of the .Net framework. It is a common lib that could be used in e.g ASP.Net MVC.

Specify the rules
Lets start with the rules. I have chosen to decorate my entities with attributes to specify the rules for them. This is as easy as:

1. Add reference to “System.ComponentModel.DataAnnotations”
2. Import namespace
3. Start decorating your classes.

This looks like:

[Serializable]
public class UserAccount
    : Entity
{
    [Required(AllowEmptyStrings = false, ErrorMessageResourceName = "UserAccountRequiredUsername", ErrorMessageResourceType = typeof(ModelValidationMessages))]
    public virtual string Username { get; set; }

    [Required(AllowEmptyStrings = false, ErrorMessageResourceName = "UserAccountRequiredPassword", ErrorMessageResourceType = typeof(ModelValidationMessages))]
    public virtual string Password { get; set; }

    [Required(AllowEmptyStrings = false, ErrorMessageResourceName = "UserAccountRequiredEmail", ErrorMessageResourceType = typeof(ModelValidationMessages))]
    public virtual string Email { get; set; }
}

I have not created any custom attribute to take care of specific validation like an “EmailAttribute”, but it can be done. I have chosen to go with resources, but you can go with simple errormessages which would look like:

[Required(AllowEmptyStrings = false, ErrorMessage="You must provide an username.")]
public virtual string Username { get; set; }

Validate an entity
In this example I’m performing the validation in my services. This is something that isn’t necessary. E.g if you are using the new MVC 2 the default modelbinder can handle the validation for you.

To fulfill “DRY” (Dont repeat yourself) I have created a base class for my services, which contains a helper-method that validates entities. The method is “ValidateEntity”. It returns an instance of my EntityValidationResult-class which contains the violations. I’m using this instance to determine if the entity should be persisted or not. The violations are passed back to the serviceconsumer via a ServiceResponse, so I don’t throw any ugly business exceptions.

public class SecurityService : Service, ISecurityService
{
    public SecurityService(IEntityStore entityStore)
        : base(entityStore)
    {
    }

    public ServiceResponse<UserAccount> SetupNewUserAccount(UserAccount userAccount)
    {
        var validationResult = ValidateEntity<UserAccount>(userAccount);

        if (!validationResult.HasViolations)
        {
            EntityStore.AddEntity(userAccount);
            EntityStore.SaveChanges();
        }

        return new ServiceResponse<UserAccount>(userAccount, validationResult);
    }
}

The ValidateEntity method is really simple, since it just consumes another object, my EntityValidator. The code for this looks like:

In the baseclass: “Service”:

protected EntityValidationResult ValidateEntity<T>(T entity)
    where T : IEntity
{
    return new EntityValidator<T>().Validate(entity);
}
public class EntityValidator<T> where T : IEntity
{
    public EntityValidationResult Validate(T entity)
    {
        var validationResults = new List<ValidationResult>();
        var vc = new ValidationContext(entity, null, null);
        var isValid = Validator.TryValidateObject(entity, vc, validationResults);

        return new EntityValidationResult(validationResults);
    }
}

The EntityValidator just consumes classes found in the System.ComponentModel.DataAnnotations library and returns eventual violations by wrapping them in my EntityValidationResult-class.

[Serializable]
public class EntityValidationResult
{
    public IList<ValidationResult> Violations { get; private set; }
    public bool HasViolations
    {
        get { return Violations.Count > 0; }
    }

    public EntityValidationResult(IList<ValidationResult> violations = null)
    {
        Violations = violations ?? new List<ValidationResult>();
    }
}

Handle the violations
Since I’m just fiddling a bit I have a simple consoleapplication which only outputs the errors:

private static void IfFailedServiceOperationInformUser<T>(ServiceResponse<T> serviceResponse)
{
    if (serviceResponse.Status == ServiceResponseStatuses.Succeeded)
        return;

    Console.WriteLine("Service failed!");

    if (serviceResponse.ValidationResult.HasViolations)
    {
        Console.WriteLine("Violations are:");
        foreach (var violation in serviceResponse.ValidationResult.Violations)
        {
            foreach (var member in violation.MemberNames)
                Console.WriteLine("\t+" + member);

            Console.WriteLine("\t" + violation.ErrorMessage);
        }
    }
}

Thats it for now. As always you can download a complete example, which has evolved since part 1 of this post-series.

//Daniel

Entity framework 4 – Part 4 – Autoregister Entitymappings

This post is part of a serie of posts where I have been fiddeling a bit with Entity framework 4 Beta 2 and extension CTP2. The example code has evolved during the writing of this series and the goal has been to create infrastructure for persisting my entities without the need of Entity framework designers, attributes etc.

Part 1 – Getting started
Part 2 – Relationships between non public members
Part 3 – Adding pluralization support to a non strongly typed ObjectContext.

Download the code.

For this post I have made the EfEntityStore-class non-abstract, so that you can consume it directly. I have also implemented a method that Auto-registers your EntityMapping-classes. So to get entities stored in your database you need to:

1. Define a connection string
2. Create your entity classes
3. Create classes that defines the mapping for your entities
4. Create an instance of the EfEntityStore and register your mappings and you’r done.
5. Consume it.

Step 1 – Define connectionstring
Note! You don’t need to create the database. The entitystore will do this for you when you call:
EnsureCleanDatabaseExists or EnsureDatabaseExists.

<connectionStrings>
  <add name="Test" connectionString="Data Source=.\sqlexpress;Initial Catalog=Christmas;Integrated Security=True;MultipleActiveResultSets=True" providerName="System.Data.SqlClient"/>
</connectionStrings>

Step 2 – Create entities
I have choosen to have a baseclass for all my entities.

[Serializable]
public abstract class Entity : IEntity
{
    public virtual int Id { get; set; }
}

[Serializable]
public class UserAccount
    : Entity
{
    public virtual string Username { get; set; }
    public virtual string Password { get; set; }
    public virtual string Email { get; set; }
}

Step 3 – Create entitymapping classes
For ease the autoregistration in Step 4 I have choosen to create a “dummy interface” that I implement in all my mapping classes, but it isn’t necessary if you don’t will use the generic autoregistration of your mappings.

public interface IChristmasEntityMapping
{
}

[Serializable]
public class UserAccountMapping : EntityConfiguration<UserAccount>, IChristmasEntityMapping
{
    public UserAccountMapping()
    {
        HasKey(u => u.Id);
        Property(u => u.Id).IsIdentity();

        Property(u => u.Email)
            .IsRequired()
            .IsNotUnicode()
            .MaxLength = 150;

        Property(u => u.Username)
            .IsRequired()
            .IsUnicode()
            .MaxLength = 20;

        Property(u => u.Password)
            .IsRequired()
            .IsUnicode()
            .MaxLength = 20;
    }
}

Step 4 & 5
Create an EntityStore instance and register the mappings. Then your done and you can start consuming it.

using(var es = new EfEntityStore("Test")) //Test is the name of the connection string
{
	es.MapEntities<IChristmasEntityMapping>();
	
	es.EnsureCleanDatabaseExists(); //Creates a new database.

	var userAccount =
		new UserAccount
			{
				Username = "littleben",
				Password = "ilovesnow",
				Email = "ben@thelittles.com"
			};

	es.SaveChanges();
}

In the donwloadable code I have implemented more entities and shown how StructureMap can help you with setting up the entitystore and a service.

Download the code and have fun with it.

The code below is not necessary, it only shows how you would use StructureMap to create an Entitystore and a service that consumers it.

public static class IoCContainer
{
	private static readonly Container _container;

	static IoCContainer()
	{
		_container = new Container();

		RegisterEntityStore();
		RegisterServices();

		//Debug.WriteLine(_container.WhatDoIHave());
	}

	private static void RegisterEntityStore()
	{
		_container.Configure(x => x
			.ForRequestedType<IEntityStore>()
			.CacheBy(InstanceScope.Singleton)
			.TheDefault.Is.OfConcreteType<EfEntityStore>()
			.WithCtorArg("connectionStringName").EqualTo("Test")
			.OnCreation(store => store.MapEntities<IChristmasEntityMapping>()));
	}

	private static void RegisterServices()
	{
		_container.Configure(x => x
			.ForRequestedType<ISecurityService>()
			.TheDefault.Is.OfConcreteType<SecurityService>()); //No need to specify cTor args since it will AutoMap IEntityStore from above
	}

	public static T Resolve<T>()
	{
		return _container.GetInstance<T>();
	}
}

//Daniel