Can I implement method_missing in C# 4 and have it actually return a value?

940 views Asked by At

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

3

There are 3 answers

0
Jon Skeet On

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 :)

0
AudioBubble On

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.

0
Mik Kardash On

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