Andre
Andre

Reputation: 3817

Create a Func<T> at runtime and set it on a target object

I have a class that declares a property Func that it wants to create

 public class ThingWithAFuncProperty
{
    public Func<string> CreateSomething { get; set; }
}

I have an injector class that uses an ioc container to create a Func and inject it to the property:

EDIT: Sorry i actually use the wrong type to pass to getFactory but the error is the same

public class Injector
{
    bool IsFuncProperty(PropertyInfo property)
    {
        return typeof(Func<>).IsAssignableFrom(property.PropertyType);
    }

    public T FactoryMethod<T>()
    {
        return this.iocContainer.Resolve<T>();
    }

    object GetFactory(Type type)
    {
        var mi = this.GetType().GetMethod("FactoryMethod", BindingFlags.Public |
            BindingFlags.Instance | BindingFlags.NonPublic);
        var targetMethod = mi.MakeGenericMethod(type);
        Type funcType = typeof(Func<>).MakeGenericType(type);
        return Delegate.CreateDelegate(funcType, targetMethod);
    }

    public void Inject(object instance)
    {
        foreach (var property in instance.GetType().GetProperties())
        {
            if (IsFuncProperty(property))
            {
                //property.SetValue(instance, GetFactory(property.PropertyType), null);
                 var funcArgType = property.PropertyType.GetMethod("Invoke").ReturnType;
                 property.SetValue(instance, GetFactory(funcArgType), null);
            }
        }
    }
}

It doesnt work and i keep ketting the error that the delegate cannot bind to the target type, can someone help me to get this to work please

Upvotes: 0

Views: 832

Answers (1)

CodesInChaos
CodesInChaos

Reputation: 108790

CreateDelegate(Type, MethodInfo)
Creates a delegate of the specified type to represent the specified static method.

It's an instance method. So you need to either pass in an instance:

CreateDelegate(funcType, this, targetMethod)

Upvotes: 3

Related Questions