在asp.net core中,AddSingleton方法确实保证了工厂只会执行一次,也就是说在整个应用程序生命周期中只会创建一个单例实例。
以下是一个示例代码,演示了AddSingleton方法只会执行一次,即使在多次请求中调用该方法也是如此:
// Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton();
services.AddSingleton();
}
// MySingleton.cs
public class MySingleton
{
public MySingleton()
{
Console.WriteLine("MySingleton instance created.");
}
}
// MyTransient.cs
public class MyTransient
{
public MyTransient(MySingleton mySingleton)
{
Console.WriteLine("MyTransient instance created with MySingleton dependency.");
}
}
// HomeController.cs
public class HomeController : Controller
{
private readonly MyTransient _myTransient1;
private readonly MyTransient _myTransient2;
public HomeController(MyTransient myTransient1, MyTransient myTransient2)
{
_myTransient1 = myTransient1;
_myTransient2 = myTransient2;
}
public IActionResult Index()
{
return Content("Hello World!");
}
}
// 输出:
// MySingleton instance created.
// MyTransient instance created with MySingleton dependency.
// MyTransient instance created with MySingleton dependency.
注意,在上面的示例中,我们通过添加两个MyTransient依赖项来测试AddSingleton方法是不是只执行一次工厂。结果证明,只有一个MySingleton实例被创建,因此AddSingleton确实保证工厂只会执行一次。