Generic InjectFrom

Feb 21, 2012 at 6:38 AM
Edited Feb 21, 2012 at 7:24 AM

Hi! Thanks for your great work.

I guess someone may have previously asked this question but I couldn't find something similar in discussions.

I'm wondering why you haven't written InjectFrom extension methods in generic form :

public static TTarget InjectFrom<TTarget>(this TTarget target, params object[] source)

instead of using object as target type?

It extends all types, infers type argument from usage and have obvious benefits over current implementation.

Of course I can create my own generic extension methods but I think there might be some limitations you preferred not to use it.

Feb 21, 2012 at 10:09 AM

because you create injections to inject from anything to anything (anything in c# translates to object), not from a certain type to another one, that's why it's object

Feb 21, 2012 at 12:03 PM
Edited Feb 21, 2012 at 12:05 PM

As far a I know semantically InjectFrom should not change the type of the target and should just inject values into it. In my generic implementation you can inject from anything into an object of type TTarget (any type without limitation) and the result is of type TTarget too which is beneficial. You don't even need to mention TTarget because it's inferred by compiler. you can use my implementation in this way:

var bar = new Bar().InjectFrom(foo1).InjectFrom(foo2);

and bar is exactly of type Bar not object. Achieving the same result from current extension methods needs explicit casting to Bar:

var bar = (Bar) new Bar().InjectFrom(foo1).InjectFrom(foo2);

In fact I have used the generic methods in my project which simply wraps original non-generic methods without problem.

Am I missing something? Is there any requirement to change the type of the target object during injection?

Feb 21, 2012 at 1:16 PM

Yes, I did something like that, but something stopped me from implementing this, I will remember and get back to this

anyway you can use your own extension 

Feb 22, 2012 at 12:37 PM
Edited Feb 22, 2012 at 12:37 PM

have you named your extension InjectFrom ?, or a different name, because with "InjectFrom" it's ambiguous invocation 

Feb 22, 2012 at 5:32 PM

Yes. It seems that generic extension methods have priority over non-generic ones. For all target types except object the generic method is selected by the compiler but for object targets the original method is selected.

May 4, 2012 at 7:23 PM

Palomino, can you share your generic extension?