José F. Romaniello

Las aventuras y desventuras de un codificador.

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?


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; }


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

public class SelectableTestFixture
    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();

        ((ISelectable) customerList[0]).Selected.Should().Be.False();

        ((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(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.

| More

0 comentarios:

Publicar un comentario en la entrada