传递Lazy Instantiation的参数

时间:2016-03-10 18:44:41

标签: c# parameter-passing lazy-initialization

鉴于以下代码段,如何将成员变量_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;
    });

1 个答案:

答案 0 :(得分:2)

我相信这会奏效:

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();
    }
}