Using Lazy to store token value in a scoped service in .NET 6

If i have a service that stores a token as a lazy object, and the token is fetched inside a value factory, is that value persisted across multiple requests, or since the underlying service is scoped, lazy starts with a null value for every single request?

_token = new Lazy<Token>(() =>
{
    var token = new Token();   

    var task = Task.Run(async () =>
    {
        var response = await Login();

        token.AccessToken = response.AccessToken;
        token.RefreshToken = response.RefreshToken;
    });
    
    task.Wait();

    return token;
});

This is called in the constructor of the service:

public MyService() 
{
    if (_token is { IsValueCreated: false }) // execute logic above
}

However, MyService is registered as scoped in Startup.cs,

services.AddScoped<IMyService, MyService>();

Does this mean that the token is fetched every time service is requested (despite the fact that value factory is thread safe) or the value factory can be called only once (even if it is called from within multiple scopes)?

4

In general, any instance members of a service are bound to the lifetime of the service. So if the service itself is scoped, which in an ASP.NET Core context usually means that it only exists for the duration of a single request, then the members of that service will also only exist for that duration.

So your Lazy value is being constructed during instantiation of MyService and will be thrown away when the service goes out of scope, which happens at the end of the request.

If you want your member to persist for multiple requests, you would have to increase the lifetime of your service to singleton which means that you will only ever have one instance that is being reused. Note that this will also mean that everyone accessing your web application will end up being handled by the same service instance, so if your token is user-specific, this won’t work.

That being said, using a Lazy<T> for an asynchronous process is not a good idea to begin with. By calling .Wait() on the task, you are essentially throwing out every benefit of asynchronous execution while also opening yourself to potential deadlocks.

And also, just accessing IsValueCreated on the Lazy object will not actually run the initialization logic of the Lazy if that was your goal in the constructor.

To properly utilize the asynchronous loading process, I would suggest you to change your service into something like this:

public class MyService
{
    private Task _tokenTask;

    public async Task<Token> GetToken()
    {
        if (_tokenTask is null)
        {
            _tokenTask = LoadToken();
        }
        return _tokenTask;
    }

    private async Task<Token> LoadToken()
    {
        var token = new Token();
        
        var response = await Login();
        token.AccessToken = response.AccessToken;
        token.RefreshToken = response.RefreshToken;
    
        return token;
    }
}

So instead of having a Lazy<Token> property, you have an asynchronous method GetToken which returns a Task<Token>. That way, every consumer can properly await the token asychronously until it is loaded, and by storing the task, you still have a mechanism to cache it.

(Note that this solution – just like Lazy<T> – is not thread-safe. If your service is a scoped service, it will likely not be consumed in parallel anyway though, so that should be fine.)

2

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật