延迟实例化的传递参数

Pass Parameter for Lazy Instantiation

给定以下代码片段,如何将成员变量 _tenantContext 传递给 Lazy<CloudBlobContainer> 构造函数?

public class BlobStorage : IStorage
{
    private readonly ITenantContext _tenantContext;

    public BlobStorage(ITenantContext tenantContext)
    {
        _tenantContext = tenantContext;
    }

    private readonly Lazy<CloudBlobContainer> _blobcontainer = new Lazy<CloudBlobContainer>(() =>
    {
        var connectionString = ConfigurationManager.ConnectionStrings["FileStorage"].ConnectionString;
        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);
        CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
        CloudBlobContainer blobContainer = blobClient.GetContainerReference("attachments");
        blobContainer.CreateIfNotExists();

        return blobContainer;
    });

我相信这会奏效:

public class Foo
{
    private readonly object _bar;
    private readonly Lazy<int> _lazyInt; 

    public Foo(object bar)
    {
        _bar = bar;
        _lazyInt = new Lazy<int>(() => GetLazyObject(_bar));
    }

    private static int GetLazyObject(object init)
    {
        return init.GetHashCode();
    }
}