爱生活爱自已 發表於 2025-3-25 12:57:00

依赖项注入-键控服务

<p>  键控服务是指使用密钥注册和检索依赖项注入 (DI) 服务的机制。 通过调用 AddKeyedSingleton (或 AddKeyedScoped 或 AddKeyedTransient)来注册服务,与密钥相关联。 使用 属性指定密钥来访问已注册的服务。</p>
<p>  以往我们的接口有多个实现,在使用时想指定使用某一个服务,往往会增加一个特性,或者属性,以此确定我们需要的服务,而键控服务可以更便捷的解决这个问题,需要注意的一点,这个是 <span style="color: rgba(255, 0, 0, 1)">.NET 8</span> 的功能。</p>
<p>我们在服务注册时,使用AddKeyedSingleton、AddKeyedScoped、AddKeyedTransient 函数,可以为每一个服务指定一个key:</p>
<div class="cnblogs_code">
<pre><span style="color: rgba(0, 128, 128, 1)">1</span> builder.Services.AddKeyedSingleton&lt;ICache, BigCache&gt;(<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">big</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">);
</span><span style="color: rgba(0, 128, 128, 1)">2</span> builder.Services.AddKeyedSingleton&lt;ICache, SmallCache&gt;(<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">small</span><span style="color: rgba(128, 0, 0, 1)">"</span>);</pre>
</div>
<p>在获取时,使用&nbsp;FromKeyedServices 特性即可,或者使用&nbsp;serviceProvider.GetKeyedServices&lt;ICache&gt;("big")</p>
<div class="cnblogs_code">
<pre><span style="color: rgba(0, 128, 128, 1)">1</span>
</span><span style="color: rgba(0, 128, 128, 1)">2</span> <span style="color: rgba(0, 0, 255, 1)">public</span> ActionResult&lt;<span style="color: rgba(0, 0, 255, 1)">object</span>&gt; GetOk( ICache cache, IServiceProvider serviceProvider)
</span><span style="color: rgba(0, 128, 128, 1)">3</span> <span style="color: rgba(0, 0, 0, 1)">{<br>    //serviceProvider.GetKeyedServices&lt;ICache&gt;("big");
</span><span style="color: rgba(0, 128, 128, 1)">4</span>   <span style="color: rgba(0, 0, 255, 1)">return</span> cache.Get(<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">data-mvc</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">);
</span><span style="color: rgba(0, 128, 128, 1)">5</span> }</pre>
</div>
<p>&nbsp;</p>

</div>
<div id="MySignature" role="contentinfo">
    <p>本文来自博客园,作者:一事冇诚,转载请注明原文链接:https://www.cnblogs.com/ysmc/p/18781249</p><br><br>
来源:https://www.cnblogs.com/ysmc/p/18781249
頁: [1]
查看完整版本: 依赖项注入-键控服务