Dynamic Ninject Binding

I create a great service and use Ninjcet:

Bind<IMyObject>().To<MyObject>(); 

Since my logic level is quite large and will grow, I would like to automatically create bindings in the assembly, given that the class implements the interface.

 public void LoadAssembly() { string[] files = Directory.GetFiles(binFolder, "Logic.dll", SearchOption.AllDirectories); foreach (var file in files) { var fileName = Path.GetFileName(file); if (fileName != null && fileName.Contains("Logic")) { DynamicallyBindManagers(Assembly.LoadFrom(file)); } } } private void DynamicallyBindManagers(Assembly assembly) { var classes = FindClassesWithInterfacesInAssembly(assembly); // Remove unwanted classes for (var i = classes.Count - 1; i >= 0; i--) { if (classes[i].Name.Contains("`")) { classes.Remove(classes[i]); } } foreach (var cl in classes) { var interfaces = cl.GetInterfaces(); foreach (var myInterface in interfaces) { if (classes.Any(c => c.Name == intf.Name.Remove(0, 1))) { var myClass = classes.First(c => c.Name == intf.Name.Remove(0, 1)); Bind<myInterface >().To<myClass>(); //How can I get Bind to accept myInterface & myClass } } } } private List<Type> FindClassesWithInterfacesInAssembly(Assembly assembly) { var classes = new List<Type>(); foreach (var ti in assembly.GetTypes().Where(x => x.IsClass)) { if (ti.GetInterfaces().Any()) { classes.Add(ti); } } return classes; } 

All help was appreciated.

+4
source share
1 answer

With the Ninject Conventions extension you can do

 Bind (x => x.FromThisAssembly.SelectAllClasses.BindDefaultInterface)); 

That connects all ISomething with Something .

+2
source

Source: https://habr.com/ru/post/1493961/


All Articles