如何注册和解析具有相同接口和实现的多个应用程序生命周期范围对象? [英] How to register and resolve multiple application life time scope objects with same interface and implementation?
问题描述
有很多类似的问题,但它们似乎没有解决这个特定的用例.
根据我的配置(运行时),我试图创建某个对象(相同的实现、相同的接口)的多个实例,这些实例应该具有应用程序生命周期范围.
阅读
There a quite a couple of similar questions but they don't seem to address this specific use case.
From my configuration (run time), I am trying to create multiple instances of a certain object (same implementation, same interface) which should have an application life time scope.
Reading the doc's I see
- Scoped lifetime (as per http request)
- Transient (as per resolvure)
- Singleton (application lifetime)
So basically I need the singleton, but, I need multiple of them.
The .AddSingleton
method and overloads doesn't seem to support any named instances.
I checked out this question, but there they are using a different (Transient) scope.
I am able to put a Name
property in the interface,
Is there a way to create (and resolve) multiple similar object with the same implementation and interface with an application life time scope?
Okay, I think the AddSingleton
name is a bit inconvenient; it seems you can register multiple "singleton" instances by using .AddSingleton
.
So, basically the following setup just works:
//some class
public class Foo
{
public string Name { get; set; }
}
With registration:
services.AddSingleton(new Foo { Name = "1" });
services.AddSingleton(new Foo { Name = "2" });
And resolving will result in 2 "singletons":
//note: this is just a test to resolve them: do not use this in your code.
services.BuildServiceProvider().GetServices(typeof(Foo));
The essence of this question, and answer, is that .AddSingleton
doesn't seem to relate to the Singleton
pattern at all.
This is what I mean:
这篇关于如何注册和解析具有相同接口和实现的多个应用程序生命周期范围对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!