c# – 动态绑定Ninject

我正在建立一个大型服务,并使用Ninjcet:

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

因为我的逻辑层很大,并且会增长,所以我想在程序集中自动创建绑定,因为该类实现了一个接口.

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;
  }

所有帮助赞赏.

最佳答案 通过Ninject Conventions扩展,您可以做到

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

这将所有ISomething绑定到某个东西.

点赞