ISelectable: Mixins and LinFu

I will show you a trivial example of mixins with LinFu in this post.
Note: this is the first time I use LinFu stuff.

Sample Scenario

We have a Customer class as follows:

public class Customer
{
    public virtual int Id { get; set; }
    public virtual string FirstName { get; set; }
    public virtual string LastName { get; set; }
}

And we have a customer repository that looks as follows:

public interface ICustomerRepository
{
    ICollection<Customer> GetSomeCustomers();
}

Now, we have a user case in WPF, that needs to display the Customer data, but we need an extra bool property named “Selected”, this property will be bound to some checkbox in the GUI. How to solve this, without a CustomerDTO nor SelectableCustomer class?

Mixins

First we start with this:

public interface ISelectable
{
    bool Selected { get; set; }
}

public class Selectable : ISelectable
{
    #region ISelectable Members

    public virtual bool Selected { get; set; }

    #endregion
}

Now, I will create an extension method named “AsSelectable”, this is my test case:

[TestFixture]
public class SelectableTestFixture
{
    [Test]
    public void as_selectable_works()
    {
        var list = new List<Customer>
                       {
                           new Customer {FirstName = "José", LastName = "Romaniello"},
                           new Customer {FirstName = "Juan", LastName = "Perez"},
                           new Customer {FirstName = "Pedro", LastName = "Picolli"}
                       };
        List<Customer> customerList = list.AsSelectable().ToList();

        customerList[0].FirstName.Should().Be.EqualTo("José");
        ((ISelectable) customerList[0]).Selected.Should().Be.False();

        customerList[1].FirstName.Should().Be.EqualTo("Juan");
        ((ISelectable) customerList[1]).Selected.Should().Be.False();
    }
}

And this is the code for AsSelectable with LinFu 1.0:

public static class AsSelectableExtension
{
    private static readonly ProxyFactory refl = new ProxyFactory();

    public static IEnumerable<T> AsSelectable<T>(this IEnumerable<T> enumerable)
        where T : class
    {
        
        
        //Create a type that inherits from customer and implements ISelectable
        Type selectableCustomerType = refl.CreateProxyType(typeof (T), new[] {typeof (ISelectable)});

        foreach (T entity in enumerable)
        {
            var dynCustomer = new DynamicObject();
            dynCustomer.MixWith(entity);
            dynCustomer.MixWith(new Selectable());
            yield return (T) dynCustomer.CreateDuck(selectableCustomerType);
        }
    }
}

And for me… it looks very nice. I don’t know how to implement this with the current version of LinFu, I use the binaries from here.
This works great with WPF. I hope you like it.


blog comments powered by Disqus
  • Categories

  • Archives