5

I was trying to figure out how to implement method_missing in C# 4, based on all of 2 blog posts floating around on IDynamicObject.

What I want to do is have a Business Logic Layer that has a Repository, and if the method is missing from the Business Logic Layer, just call the Repository and pass through its result. So i have a class that looks like this:

public class CustomerServices : IDynamicObject
{
    protected CustomerRepository _Repository = new CustomerRepository();

    MetaObject IDynamicObject.GetMetaObject(Expression parameter)
    {                      
        return new RepositoryMetaObject<CustomerRepository>(_Repository, parameter);                        
    }
} 

In RepositoryMetaObect I implement the Call method like so:

    public override MetaObject Call(CallAction action, MetaObject[] args)
    {
        typeof(T).GetMethod(action.Name).Invoke(_Repository, getParameterArray(args));
        return this;            
    }

(The rest of RepositoryMetaObject code probably isn't interesting, but I've included it here: http://pastie.org/312842)

The problem I think is that I'm never doing anything with the result of the Invoke, I'm just returning the MetaObject itself.

Now when I do this:

        dynamic service = new CustomerServices();
        var myCustomer = service.GetByID(1); 

GetByID is called, but if I try to access a property on myCustomer, is just hangs.

Can anyone please help?

Complete code can be downloaded ehre: https://dl.getdropbox.com/u/277640/BusinessLogicLayer.zip

Mihai Limbășan
  • 64,368
  • 4
  • 48
  • 59
ignu
  • 158
  • 10

3 Answers3

1

I believe you need to return a new MetaObject with the returned value as a constant expression.

That's certainly what happens on this CodeProject page. Worth a try :)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

but if I try to access a property on myCustomer, is just hangs

Can you set a breakpoint on the line after service.GetByID(1)? See what you've really got back from that call. Otherwise it's hard to tell what exactly happened.

Bevan
  • 43,618
  • 10
  • 81
  • 133
0

Instead of

return this;

Try doing something like this

return RepositoryMetaObject<CustomerRepository>(
       _Repository
     , System.Linq.Expressions.Expression.Constant(returnValue, returnValueType)
);

(still not sure why, but it works for me).

Mik Kardash
  • 630
  • 8
  • 17