注册多个实现的示例:
using ConsoleDI.IEnumerableExample;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace ConsoleDI.Example;
class Program
{
static Task Main(string[] args)
{
using IHost host = CreateHostBuilder(args).Build();
_ = host.Services.GetService<ExampleService>();
return host.RunAsync();
}
static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((_, services) =>
services.AddSingleton<IMessageWriter, ConsoleMessageWriter>()
.AddSingleton<IMessageWriter, LoggingMessageWriter>()
.AddSingleton<ExampleService>());
}
获取多个实现的示例:
using System.Diagnostics;
namespace ConsoleDI.IEnumerableExample;
public class ExampleService
{
public ExampleService(
IMessageWriter messageWriter,
IEnumerable<IMessageWriter> messageWriters)
{
Trace.Assert(messageWriter is LoggingMessageWriter);
var dependencyArray = messageWriters.ToArray();
Trace.Assert(dependencyArray[0] is ConsoleMessageWriter);
Trace.Assert(dependencyArray[1] is LoggingMessageWriter);
}
}
在工厂中,可以获取所有注册的示例,然后根据需要的类型,返回具体的对象。
Transient 操作总是不同,每次检索服务时,都会创建一个新实例。
Scoped 仅随着新范围更改,但在一个范围中是相同的实例。
Singleton 操作总是相同,新实例仅被创建一次。
网友评论