views:

57

answers:

1

I'm fairly new to Ninject, but I have successfully managed to use it for DI using a custom provider.

The binding is initialised as follows

kernel = new StandardKernel();

kernel.Bind<IPatientRecordLocator>().ToProvider<PatientRecordLocatorProvider>();

and in the custom provider I call Activator.CreateInstance like so

protected override IPatientRecordLocator CreateInstance(IContext context)
{
    var name = ConfigurationManager.AppSettings["PatientRecordLocator"];
    var typeName = name.Split(',')[0];
    var assemblyName = name.Split(',')[1];
    return Activator.CreateInstance(assemblyName, typeName).Unwrap() as IPatientRecordLocator;
}

(yes, I am aware that there is no error handling, etc. in the code above :) )

and all this works like a charm.

Now, the problem I'm facing is when I introduce a new class that I wish to inject into instances of IPatientRecordLocator. The problem occurs when I add a constructor like the following to e.g. one of these classes

[Inject]
public MockPatientRecordLocator (IContactAdapter contactAdapter)
{
    ...
}

Then, for Activator.CreateInstance to work I also have to add a parameterless constructor to class MockPatientRecordLocator, i.e.

public MockPatientRecordLocator() 
{
}

So, my question is: how can I make Ninject inject an instance of a class that implements IContactAdapter into e.g. MockPatientRecordLocator? I've tried method injection, but to no avail.

I forgot to explain that what I'm trying to achieve is a kind of chained injection where an instance of class PatientRecordSummary gets injected with an instance of MockPatientRecordLocator (using constructor injection) and said instance of MockPatientRecordLocator should get injected with an instance of IContactAdapter (again using constructor injection (if possible)). The first part of the chain works, the second doesn't.

A: 

Not bad for a first question!

You want to use the Bind(Type) overload to allow registration of stuff that you dont have statically available in the context of your Load() code - do the stuff you're doing in your provider (i.e., resolving the Type) up-front. This will allow Ninject to do the object instantiation (without any requirement for a default .ctor)

IIRC two or 3 of my most recent answers also touch on this discovery/loading stuff, and have examples that should be relevant to your case.

(And you wont need to resort to [Inject] attributes when you've gotten to remove things)

Ruben Bartelink
Hi Ruben, thanks for your help (and compliment). Trying the best I can :-) In this particular setup I didn't use modules, but I'll switch to using them so that I can more easily use Bind().
norgie