-2

i couldn't use _cloudinaryConfig because of this error:

A field initializer cannot reference the nonstatic field, method, or property

I'm not sure what supposed to do

 private IAppRepository _appRepository;
 private IMapper _mapper;
 private IOptions<CloudinarySettings> _cloudinaryConfig;

 public PhotosController(
        IAppRepository appRepository,
        IMapper mapper,
        IOptions<CloudinarySettings> cloudinaryConfig)
 {
     this._appRepository = appRepository;
     this._mapper = mapper;
     this._cloudinaryConfig = cloudinaryConfig;
 }

 string cloud = _cloudinaryConfig.Value.CloudName;
 string apiKey = _cloudinaryConfig.Value.ApiKey;
 string apiSecret = _cloudinaryConfig.Value.ApiSecret;

 Cloudinary _cloudinary = new Cloudinary(new Cloudinary(
        new Account(cloud, apiKey, apiSecret)));
jps
  • 20,041
  • 15
  • 75
  • 79
hhuseyin
  • 1
  • 1
  • 1
    fields are initialized before construction, not in order of where you put them in code. – Crowcoder Jun 02 '22 at 17:13
  • @Crowcoder, minor point: yes, all fields are initialized before the constructor, but the order in which those fields are initialized does depend on where you put them in code. – Kirk Woll Jun 02 '22 at 17:35
  • could you be more specific, bc i'm not sure i got it – hhuseyin Jun 02 '22 at 17:40
  • when a class is being initialized into an object instance it does not simply run the code from the top down. [Fields are initialized before the constructor is run even](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/fields) if you defined the constructor before the fields in your .cs file. Therefore, you cannot reference `_cloudinaryConfig ` because it would be null. – Crowcoder Jun 02 '22 at 17:49
  • thanks a lot, I got better now. @Crowcoder – hhuseyin Jun 02 '22 at 17:54

1 Answers1

0

You mean something like this?

 private IAppRepository _appRepository;
 private IMapper _mapper;
 private IOptions<CloudinarySettings> _cloudinaryConfig;

 string cloud;
 string apiKey;
 string apiSecret;

 Cloudinary _cloudinary;

 public PhotosController(
        IAppRepository appRepository,
        IMapper mapper,
        IOptions<CloudinarySettings> cloudinaryConfig)
 {
     this._appRepository = appRepository;
     this._mapper = mapper;
     this._cloudinaryConfig = cloudinaryConfig;
     this.cloud = _cloudinaryConfig.Value.CloudName;
     this.apiKey = _cloudinaryConfig.Value.ApiKey;
     this.apiSecret = _cloudinaryConfig.Value.ApiSecret
     this._cloudinary = new Cloudinary(new Cloudinary(
        new Account(cloud, apiKey, apiSecret)));
 }