.Net 方面,直到最近,我一直被困在 2005 年。我知道我有很多事情要做,但由于我不喜欢低效的代码,SimpleInjector 教程中的以下代码片段(在这个问题的底部)让我有点难过。
问题出在BootStrapper()方法中,该方法用于初始化静态 SimpleInjector 容器。
在这个方法中, avar container被声明并分配了一个 new Container()。在方法结束时,方法范围container被分配给静态的、App 级别的container变量。
为什么这样做?必须有充分的理由首先将容器分配给本地范围的 var,然后最后将 var 分配给类级别的静态 Container 变量。对我来说,这似乎是一个明显的、多余的任务,但如果是这样的话,我怀疑有人会这样做。我错过了什么?
下面的代码来自 SimpleInjector 文档中的代码。我理解所有代码在做什么,我只是不明白这个额外var分配的意义。
using System.Windows;
using SimpleInjector;
public partial class App : Application
{
private static Container container; //<-- The static, class-level variable.
// Why not assign to it from the get-go?!
//...snip...
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
Bootstrap();
}
private static void Bootstrap()
{
// Create the container as usual.
var container = new Container(); //What's the point of this var?
// Register your types, for instance:
container.RegisterSingle<IUserRepository, SqlUserRepository>();
container.Register<IUserContext, WpfUserContext>();
// Optionally verify the container.
container.Verify();
// Store the container for use by the application.
App.container = container; //Couldn't we have done this from line 1 of this method?
}
}