3

Given the following code snippet, how can I pass the member variable _tenantContext into the Lazy<CloudBlobContainer> constructor?

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;
    });
Dan Forbes
  • 2,734
  • 3
  • 30
  • 60
PJDW
  • 145
  • 1
  • 4
  • 15
  • Can you please post what you've tried so far and why it is not working? – Dan Forbes Mar 10 '16 at 19:12
  • Possible duplicate of [Pass parameters to constructor, when initializing a lazy instance](http://stackoverflow.com/questions/4414363/pass-parameters-to-constructor-when-initializing-a-lazy-instance) – Dan Forbes Mar 10 '16 at 19:31
  • I tried it that way, but it wasn't working. – PJDW Mar 10 '16 at 20:43

1 Answers1

6

I believe this will work:

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();
    }
}
Dan Forbes
  • 2,734
  • 3
  • 30
  • 60