[英]C# and Ninject question, Inheriting a class runs a method, but how does this happen behind the scene?
我似乎无法在这里找到几个相关问题的正确答案。
我正在从一篇文章中学习 Ninject(在 C# 中创建了一个控制台应用程序),我创建了一个 class 我命名为 DILoader 并继承了 NinjectModule:
public class DILoader : NinjectModule
{
public override void Load()
{
Bind<ICustomer>().To<RetailCustomer>();
Bind<ICustomer>().To<WholesaleCustomer>();
}
}
所以在启动时:
static void Main(string[] args)
{
var kernel = new StandardKernel();
kernel.Load(Assembly.GetExecutingAssembly()); }
我的问题是,上面的 Load() 方法被触发了。 当 NinjectModule 有一个抽象的 Load() 方法时,这是如何在幕后发生的? 这是在哪里触发的?
谢谢
这里: https://github.com/ninject/Ninject/blob/master/src/Ninject/Modules/NinjectModule.cs
在 NinjectModule 内部,
/// <summary>
/// Called when the module is loaded into a kernel.
/// </summary>
/// <param name="kernelConfiguration">The kernel configuration that is loading the module.</param>
/// <param name="settings">The ninject settings.</param>
/// <exception cref="ArgumentNullException"><paramref name="kernelConfiguration"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentNullException"><paramref name="settings"/> is <see langword="null"/>.</exception>
public void OnLoad(IKernelConfiguration kernelConfiguration, INinjectSettings settings)
{
Ensure.ArgumentNotNull(kernelConfiguration, nameof(kernelConfiguration));
Ensure.ArgumentNotNull(settings, nameof(settings));
this.KernelConfiguration = kernelConfiguration;
this.Components = this.KernelConfiguration.Components;
this.Settings = settings;
this.Load();
}
然后在KernelConfiguration实现中,您可以看到它在这里调用 module.OnLoad(...),
/// <summary>
/// Loads the module(s) into the kernel.
/// </summary>
/// <param name="modules">The modules to load.</param>
/// <exception cref="ArgumentNullException"><paramref name="modules"/> is <see langword="null"/>.</exception>
public void Load(IEnumerable<INinjectModule> modules)
{
Ensure.ArgumentNotNull(modules, nameof(modules));
modules = modules.ToList();
foreach (INinjectModule module in modules)
{
if (string.IsNullOrEmpty(module.Name))
{
throw new NotSupportedException(ExceptionFormatter.ModulesWithNullOrEmptyNamesAreNotSupported());
}
if (this.modules.TryGetValue(module.Name, out INinjectModule existingModule))
{
throw new NotSupportedException(ExceptionFormatter.ModuleWithSameNameIsAlreadyLoaded(module, existingModule));
}
module.OnLoad(this, this.Settings);
this.modules.Add(module.Name, module);
}
foreach (INinjectModule module in modules)
{
module.OnVerifyRequiredModules();
}
}
看看源头,你可以更彻底地追踪它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.