I have an MVC4 app that uses reflection to load controllers at run time. These controllers as well as the main app use Ninject to inject things into the constructors.
Each dynamic controller maintains a list of all the bindings it needs and stores them as a Ninject module that the main app loads at run time.
I'm having issues at the moment where multiple dynamic controllers contain the same bindings. I want the dynamic controllers to be self contained so i don't want to remove the bindings from inside the controller projects and i don't really want to have to parse a txt or xml document to read all the bindings.
Is there a way to remove duplicate bindings or tell Ninject to use the first binding it comes across if there is more than one.
Loading all the referenced assmblies bindings
public static StandardKernel LoadNinjectKernel(IEnumerable<Assembly> assemblies)
{
var kernel = new StandardKernel();
foreach (var asm in assemblies)
{
asm
.GetTypes()
.Where(t =>
t.GetInterfaces()
.Any(i =>
i.Name == typeof(INinjectBootstrapper).Name))
.ToList()
.ForEach(t =>
{
var ninjectModuleBootstrapper =
(INinjectBootstrapper)Activator.CreateInstance(t);
kernel.Load(ninjectModuleBootstrapper.GetModules());
});
}
return kernel;
}
Binding Class
public class NinjectBindings : Ninject.Modules.NinjectModule
{
public override void Load()
{
Bind<IDMSService>().To<DMSService>();
Bind<ICaseManagerRepo>().To<CaseManagerRepo>();
}
}
Controller Factory
protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
{
if (controllerType != null)
{
return (IController)kernel.Get(controllerType);
}
else
{
return base.GetControllerInstance(requestContext, controllerType);
}
}