0

In writing a Cake addin I have the following:

public static class Aliases
{
[CakeMethodAlias]
public static VaultInfo GetVaultInfo(this ICakeContext context, string userName)
{
    Debugger.Launch();
    return new VaultInfo("","","","","");
} 
}

In my script build.cake I have:

private static VaultInfo r = GetVaultInfo("user");

When I run this with Cake.exe build.cake I get

Error: <path>/setup.cake(10,30): error CS0120: An object reference is required for the non-static field, method, or property 'GetVaultInfo(string)'

It sounds like something obviously wrong in the cake script but...!

aateeque
  • 2,161
  • 5
  • 23
  • 35

2 Answers2

2

Remove the static modifier from you field.

Instead of having

private static VaultInfo r = GetVaultInfo("user");

change it to

private VaultInfo r = GetVaultInfo("user");

Remember standard C# rules apply, static variables are initialized before any instances is called. (Or so I believe)

Naktibalda
  • 13,705
  • 5
  • 35
  • 51
AdmiringWorm
  • 111
  • 4
  • Wrong; there is nothing wrong with calling a static method in a static initializer. – SLaks Jan 19 '17 at 15:20
  • @SLaks Not wrong. It's an extension method and expects to be called on an instance or for you to pass in an instance. – smoyer Jan 19 '17 at 17:06
  • That won't work either; extension methods require explicit `this`. Plus, `this` isn't available in instance initializers. And, that's the wrong error message. – SLaks Jan 19 '17 at 17:20
  • @SLaks this is the correct answer; the Cake script host hasn't initialized at that point so `GetVaultInfo()` cannot be as an alias. – aateeque Jan 19 '17 at 18:35
0

I've never used cake, but I can tell you that what you have isn't valid C#. Your method is setup as an extension method, but you're trying to call it from a static context.

Change it to this and it should work, and it doesn't look like you're using ICakeContext in the method anyway.

[CakeMethodAlias]
public static VaultInfo GetVaultInfo(string userName)
{
    Debugger.Launch();
    return new VaultInfo("","","","","");
}

If you actually need ICakeContext, you'd have to call that method on an instance of the ICakeContext class.

smoyer
  • 7,932
  • 3
  • 17
  • 26
  • Could you post your build.cake? I think you have to call those extension methods within a task. Because you're calling it from a static context still so I'm not sure where it'd get the ICakeContext. – smoyer Jan 19 '17 at 14:22
  • @Steveadoo the ICakeContext is provided by the Cake Script Host once the alias assembly is compiled. This is done during the initialization where we use Roslyn or Mono to compile the script. – Gary Ewan Park Jan 19 '17 at 14:28
  • Yeah but he's still calling it from a static context. – smoyer Jan 19 '17 at 14:55