Web 中的 SimpleInjector Singleton LifeStyle
SimpleInjector Singleton LifeStyle in Web
假设我有一个 IOC 容器。我使用那个容器来注册一个单身生活方式的记录器:
var container = new Container();
container.Register<ILogger, Logger>(LifeStyle.Singleton);
现在我使用这个单例时,只会为它创建一个实例。
但我的问题是,例如 ASP.NET 网络。对于那个用户或访问我的网站的每个用户,整个应用程序使用的是同一个实例吗?
如果它适用于每个用户并且记录器正忙于记录某些内容而另一个用户也尝试记录某些内容怎么办?那会引发错误吗? (我的意思是……记录器的最佳实践是什么?)
简单注入器文档states:
There will be at most one instance of the registered service type and the container will hold on to that instance until the container is disposed or goes out of scope. Clients will always receive that same instance from the container. [...] Simple Injector guarantees that there is at most one instance of the registered Singleton inside that Container instance, but if multiple Container instances are created, each Container instance will get its own instance of the registered Singleton.
文档的 Another part 描述了:
You should typically create a single Container instance for the whole application (one instance per app domain); Container instances are thread-safe.
这意味着由于您通常只会创建一个容器实例,因此 Singleton 注册对于整个 AppDomain 将只有一个实例。所以每个用户和每个请求都将使用同一个实例。
您有责任确保此类实现是线程安全的并且可以由多个线程并行使用。
如果您不能保证线程安全,此类实例应注册为 Scoped 或 Transient.
您应该查阅所用日志记录库的文档以了解该类型的实例是否是线程安全的。
与其在您的代码中注入第三方库抽象,不如考虑描述的替代设计 here。
假设我有一个 IOC 容器。我使用那个容器来注册一个单身生活方式的记录器:
var container = new Container();
container.Register<ILogger, Logger>(LifeStyle.Singleton);
现在我使用这个单例时,只会为它创建一个实例。 但我的问题是,例如 ASP.NET 网络。对于那个用户或访问我的网站的每个用户,整个应用程序使用的是同一个实例吗?
如果它适用于每个用户并且记录器正忙于记录某些内容而另一个用户也尝试记录某些内容怎么办?那会引发错误吗? (我的意思是……记录器的最佳实践是什么?)
简单注入器文档states:
文档的There will be at most one instance of the registered service type and the container will hold on to that instance until the container is disposed or goes out of scope. Clients will always receive that same instance from the container. [...] Simple Injector guarantees that there is at most one instance of the registered Singleton inside that Container instance, but if multiple Container instances are created, each Container instance will get its own instance of the registered Singleton.
Another part 描述了:
You should typically create a single Container instance for the whole application (one instance per app domain); Container instances are thread-safe.
这意味着由于您通常只会创建一个容器实例,因此 Singleton 注册对于整个 AppDomain 将只有一个实例。所以每个用户和每个请求都将使用同一个实例。
您有责任确保此类实现是线程安全的并且可以由多个线程并行使用。
如果您不能保证线程安全,此类实例应注册为 Scoped 或 Transient.
您应该查阅所用日志记录库的文档以了解该类型的实例是否是线程安全的。
与其在您的代码中注入第三方库抽象,不如考虑描述的替代设计 here。