You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何Microsoft Graph示例中GraphSdkHelper被注册为Transient?

Why is GraphSdkHelper registered as Transient in the Microsoft Graph ASP.NET Core sample?

Great question! Let's break down the reasoning behind registering GraphSdkHelper as transient, even though it internally instantiates key classes with new:

  • Preventing state contamination across requests
    The GraphSdkHelper is typically responsible for creating and configuring a GraphServiceClient instance tailored to the current request/user. Since GraphServiceClient holds request-specific data like authentication tokens, reusing a single instance (via singleton) would risk sharing tokens or user context between different requests. Registering GraphSdkHelper as transient ensures every injection gets a fresh instance, which in turn generates a fresh GraphServiceClient isolated to the current operation.

  • Aligning with Microsoft Graph best practices
    Microsoft explicitly recommends avoiding singleton instances of GraphServiceClient because it caches authentication state. By making GraphSdkHelper transient, we follow this guidance: each helper instance creates a client that's scoped to the immediate need, avoiding unintended reuse of stale tokens or user-specific context.

  • Complementing the singleton GraphAuthProvider
    Notice that IGraphAuthProvider is registered as a singleton—this makes sense because the auth provider is stateless, handling token acquisition logic that doesn't change across requests. The transient GraphSdkHelper depends on this singleton provider, so we get the best of both worlds: reuse the efficient, stateless auth logic while ensuring each client creation is fresh and request-safe.

  • Future-proofing the code
    Even if the current implementation uses new for internal classes, registering GraphSdkHelper as transient keeps the code flexible. If future updates add stateful dependencies or modify how the helper works, we won't have to adjust the DI registration to avoid bugs related to shared state.

Sample code reference from Startup.cs:

services.AddSingleton<IGraphAuthProvider, GraphAuthProvider>(); 
services.AddTransient<IGraphSdkHelper, GraphSdkHelper>();

内容的提问来源于stack exchange,提问作者Jim O'Neil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:07:50