2

I'm using Ninject.Web.WebApi-RC in an MVC 4 Website.

In my NinjectWebCommon.cs file I have:

kernel.Bind<IA>().To<A>();
kernel.Bind<byte[]>().ToConstant(new byte[1]).WhenTargetHas<AKeyAttribute>();

In my WebApi controller I'm requesting an IKernel in the constructor (just trying to troubleshoot). I'm calling Get<IA>() in my controller constructor. The constructor for A looks like:

public A([AKey] byte[] key)

where AKeyAttribute is a class that extends Attribute. My issue is that when the code gets inside of the constructor for A its argument is a byte of length 0, not 1.

Any ideas? Thanks!

EDIT

This is incredibly weird. I've changed the constructor of A to:

public A([AKey] string test)

And my NinjectWebCommon.cs file to:

kernel.Bind<string>().ToConstant("Test").WhenTargetHas<AKeyAttribute>();

And then "Test" is indeed being injected into the controller. However when I do:

public A([AKey] string[] test)
kernel.Bind<string[]>().ToConstant(new string[] { "Test" }).WhenTargetHas<AKeyAttribute>();

That doesn't work.

I'm guessing when you do an array of something in a class' constructor it's expecting multi-injection? Is there a way to override this?

4

1 回答 1

0

这就是我最终做的事情。如果您需要将常量数组注入构造函数,并且可以更改构造函数,一种方法是注入Func<>相关类型的 a ,如下所示:

byte[] hash = ...
kernel.Bind<Func<byte[]>>().
            ToConstant(new Func<byte[]>(() => hash)).
            WhenTargetHas<AKeyAttribute>();

public A([AKey] Func<byte[]> key)

(然后显然Func<>在你的构造函数中调用。)

于 2013-08-23T11:37:13.730 回答