好吧,这通常发生在声明绑定但加载其他模块时,该模块试图解析尚未加载的绑定。发生这种情况是因为List<INinjectModule> 的顺序可能不正确。
如果您认为是这种情况。遵循此决议。
我们的想法是每个程序集都有一个bootstapper,引导程序将负责按逻辑顺序加载模块。
让我们考虑一个引导程序的接口(我们将使用它来查找程序集中的引导程序)
public interface INinjectModuleBootstrapper
{
IList<INinjectModule> GetModules();
}
现在考虑为您的 DataAccess 程序集实现 INinjectModuleBootstrapper:
public class DataAccessBootstrapper : INinjectModuleBootstrapper
{
public IList<INinjectModule> GetModules()
{
//this is where you will be considering priority of your modules.
return new List<INinjectModule>()
{
new DataObjectModule(),
new RepositoryModule(),
new DbConnectionModule()
};
//RepositoryModule cannot be loaded until DataObjectModule is loaded
//as it is depended on DataObjectModule and DbConnectionModule has
//dependency on RepositoryModule
}
}
这就是您为所有程序集定义Bootstrapper 的方式。现在,从您的程序启动开始,我们需要加载所有模块的StandardKernel。我们会这样写:
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
return BootstrapHelper.LoadNinjectKernel(assemblies);
我们的BootstrapperHelper 类是:
public static class BootstrapHelper
{
public static StandardKernel LoadNinjectKernel(IEnumerable<Assembly> assemblies)
{
var standardKernel = new StandardKernel();
foreach (var assembly in assemblies)
{
assembly
.GetTypes()
.Where(t =>
t.GetInterfaces()
.Any(i =>
i.Name == typeof(INinjectModuleBootstrapper).Name))
.ToList()
.ForEach(t =>
{
var ninjectModuleBootstrapper =
(INinjectModuleBootstrapper)Activator.CreateInstance(t);
standardKernel.Load(ninjectModuleBootstrapper.GetModules());
});
}
return standardKernel;
}
}