Search code examples
c#dependency-injectionninjectinversion-of-control

Injecting Custom Args using Method Injection


I am newbie to Ninject. I have seen Constructor Injection with Custom Arguments can be done by using

Bind<>().To<>().WithConstructorArguments("Name","Value")

Then I thought to, try a sample of Method Injection with some custom arguments like as below:

[Inject]
public void DoSomething(int a,string data,double b, etc...)
{

}

But, I got tucked on how to pass data, to those arguments..

I have checked the intellisense and seen functions like, WithConstructorArgument, WithPropertyValue and so I believed there should/may be a option to achieve this one..

May I know, how to solve this case.

Thanks in advance.


Solution

  • You can't use method injection like that. What you can do, however, is using the OnActivation extension like:

    Bind<>().To<>()
        .OnActivation(x => x.DoSomething(5, "hello world", 3.5,...);    
    

    It gets executed after ninject calls the ctor and perform property / method injection. So exactly once per instance. Effectively this should just be what you're looking for.