Less specific using statements conflicting with more specific ones
-
07-06-2021 - |
Question
Can anyone explain this behavior and what the solution is?
I installed Ninject.MVC3 via nuget, this creates a file in the App_Start folder called NinjectWebCommon.cs with the namespace like this:
namespace MvcApplication1.App_Start {
...
using Ninject;
using Ninject.Web.Common;
...
}
Now, I want to create an NinjectModule and am having some issues with the Ninject namespace being recognized.
namespace MvcApplication1.Ninject.Modules {
using Ninject.Modules
...
}
As soon as I add the using statement in the module, NinjectWebCommon.cs can no longer compile. If I place the using outside the namespace, it still won't compile.
If, however, i change the namespace for my module to MvcApplication1.Foo, then it works fine either way.
Why would naming this MvcApplication1.Ninject.Modules (or even just MvcApplication1.Ninject) cause NinjectWebCommon.cs to no longer find it's references? I thought the purpose of namespaces was to prevent this sort of thing?
Solution
Using statements within a namespace search in the child namespace of the current namespace and all its ancestors before looking at the global name space. E.g. If you have a namespace MvcApplication1.A you can write
using A
Instead of
using MvcApplication1.A
Because of this, your example is interpreted by the compiler as
namespace MvcApplication1.Ninject.Modules {
using MvcApplication1.Ninject.Modules
...
}
You can force that the compiler looks only in the global namespace like this:
namespace MvcApplication1.Ninject.Modules {
using global::Ninject.Modules
...
}