I have an ASP.NET MVC 3 application with Ninject v2.2.1.4. Everything worked fine, and then we started to see how Ninject is trying to create our DbContext using a constructor with a parameter over a constructor without parameters. Here are the bindings:
kernel.Bind<MyContext>().ToSelf().InRequestScope(); kernel.Bind<IUnitOfWork>().ToMethod(ctx => ctx.Kernel.Get<MyContext>()); kernel.Bind<DbContext>().ToMethod(ctx => ctx.Kernel.Get<MyContext>());
MyContext is a DbContext object that also implements the IUnitOfWork interface. I configured it so that the same context is entered into several repositories that are used in the same request. MyContext constructors look like this:
public MyContext() { } public MyContext(string connectionString) { } public MyContext (long accountID) { } public MyContext (Connection connection) { }
There are different constructors for different applications, since they all use the same MyContext class. Looking at the bindings that you might think when the MyContext class was requested, the constructor without parameters would be called, but for some reason this is not the case. One with the long parameter accountID is called, even if no account identifier is specified. This explicitly makes and excludes the statement that "There are no suitable bindings and the type is not self-switching." It actually throws an exception when trying to create IUnitOfWork.
If I comment on the last three constructors, everything works fine, and the constructor without parameters is used. If I comment on any two of the parameterized constructors, it tries to use the other, and not without parameters.
Suggestions offered by Ninject:
Suggestions: 1) Ensure that you have defined a binding for long. 2) If the binding was defined in a module, ensure that the module has been loaded into the kernel. 3) Ensure you have not accidentally created more than one kernel. 4) If you are using constructor arguments, ensure that the parameter name matches the constructors parameter name. 5) If you are using automatic module loading, ensure the search path and filters are correct.
We have nothing for 1, as we do not want it. I'm not sure what 2 and 5 mean. I don't think we made 3, and we don't 4.
Any thoughts on why the constructor without parameters would not use in this scenario.
Nick Olsen
source share