Question

What I mean is - when I user Ninject for my controllers it automatically injects all fields to the controller constructor, now... I have class called CommonMethods in my project, and I need to pass certain fields from the controller to that class in order to use it (this class contains non-static methods only, so it needs to be created), of course I can do it by hand like this:

CommonMethods cm = new CommonMethods(someVarFromCurrentcontroller, someTherVar,... and so on..);
cm.SomeMethod();

However the above will force me to manually update the code, every time I modify "CommonMethods" constructor, so the question is - is there any way to use Ninject here? I would like to do something like:

IKernel k = new StandardKernel();
CommonMethods c = k.Get<CommonMethods>();

But if I try the above a get errors saying "No matching bindings are available for X" (but they are there). I guess this is because I use new kernel and not the one that is used on app startup. How can I resolve this issue?

Thanks in advance.

Best regards.

Edit 1:

This is how my controllers constructors look like:

private EFDbContext context;

private ISaleActionRepository saleActionRepository;
private IUserRepository userRepository;

public TestController(ISaleActionRepository saleActionRepository, IUserRepository userRepository, EFDbContext context)
{
    this.saleActionRepository = saleActionRepository;
    this.userRepository = userRepository;

    this.context = context;
}

And this is how my CommonMethods controller look like:

private IUserRepository userRepository;
private IPaymentRepository paymentRepository;
private IFunctionalityPackageRepository functionalityPackageRepository;
private ISettingRepository settingRepository;

public CommonMethods(IUserRepository userRepository, IPaymentRepository paymentRepository, IFunctionalityPackageRepository functionalityPackageRepository, ISettingRepository settingRepository)
{
    this.userRepository = userRepository;
    this.paymentRepository = paymentRepository;
    this.functionalityPackageRepository = functionalityPackageRepository;
    this.settingRepository = settingRepository;
}
Was it helpful?

Solution

Just add the CommonMethods service as argument in your TestController's constructor and let the container build up the complete object graph. Such object graph can be many layers deep.

private readonly EFDbContext context;
private readonly ISaleActionRepository saleActionRepository;
private readonly IUserRepository userRepository;
private readonly CommonMethods commonMethods;

public TestController(ISaleActionRepository saleActionRepository, 
    IUserRepository userRepository, EFDbContext context, CommonMethods commonMethods)
{
    this.saleActionRepository = saleActionRepository;
    this.userRepository = userRepository;
    this.context = context;
    this.commonMethods = commonMethods;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top