0
votes

I have started to use Ninject today because Structuremap let me down big time.

I hit an issue when I began registering the same types with the same interfaces but I have have named them (as shown below).

kernel.Bind<IDataContextAsync>().To<DbGeoContext>().InRequestScope().Named("DbGeoContext");
kernel.Bind<IDataContextAsync>().To<DbEspContext>().InRequestScope().Named("DbEspContext");

IParameter geoUnitOfWorkDbContext = new ConstructorArgument("dataContext", kernel.Get<IDataContextAsync>("DbGeoContext"));
IParameter espUnitOfWorkDbContext = new ConstructorArgument("dataContext", kernel.Get<IDataContextAsync>("DbEspContext"));

kernel.Bind<IUnitOfWorkAsync>().To<UnitOfWork>().Named("UnitOfWorkGeoContext").WithConstructorArgument(geoUnitOfWorkDbContext);
kernel.Bind<IUnitOfWorkAsync>().To<UnitOfWork>().Named("UnitOfWorkEspContext").WithConstructorArgument(espUnitOfWorkDbContext);

**Fails here with: Error activating IDataContextAsync

More than one matching bindings are available.**

var t1 = kernel.Get("UnitOfWorkGeoContext"); var t2 = kernel.Get("UnitOfWorkEspContext");

Could someone help me figure out what is going on here and how to fix it?

I understand at runtime Ninject wont be able to figure out which instance to inject, but I though this was what the 'Named' instances was for?

Thanks

1
The constructor must have the Named attribute - David Pine
Hi This is not a duplicate due to me trying to achieve all of the binding logic in the RegisterService method. I don't want to have to include the ninject library into my Repository layer. - Csharper
The answer is still the same, since you are using .Named("SomeUniqueString") -- you must have the Named attribute in the constructor so that it knows how to resolve. - David Pine

1 Answers

0
votes

When using Ninject to target multiple implementations of the same interface, you need to do so with the .Named call as you have done. But you also need to add the Named attribute on the constructor so that Ninject know which implementation to resolve.

As shown here:

https://github.com/ninject/ninject/wiki/Contextual-Binding#simple-constrained-resolution-named-bindings

Example

class SomeClassThatConsumesOneOfYourImplementations
{
    public SomeClassThatConsumesOneOfYourImplementations(
        [Named("DbGeoContext")] IDataContextAsync context)
    {
        // Constructor logic...
    }
}