[英]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.