RLH*_*RLH 1 .net c# dependency-injection c#-4.0 simple-injector
.Net-直到最近,我一直困在2005年.我知道我有很多事要做,但由于我不喜欢效率低下的代码,因此SimpleInjector教程中的以下代码片段(在本问题的底部)让我感到有点难过.
问题出在该BootStrapper()方法中,该方法用于初始化静态SimpleInjector容器.
在此方法中,var container声明a 并为其分配新的Container().在方法结束时,方法范围container随后被分配给静态的App级container变量.
为什么这样做?必须有一个很好的理由将容器首先分配给local-scope 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?
}
}
Run Code Online (Sandbox Code Playgroud)