I am a new C# developer and I am trying to re-use the API client that I built based on the Ultimate RestSharp Client in ASP.NET and C# explained in this post. I was able to create all the classes and prerequisites mentioned in the article, but I am unable to use the client class right now over some places in my application
Here's the client code:
public class UsersClient : BaseClient
{
public UsersClient (ICacheService cache, IDeserializer serializer, IErrorLogger errorLogger)
: base(cache, serializer, errorLogger, "http://yourBaseUrl.com") { }
public User GetByID(int id)
{
RestRequest request = new RestRequest("users/{id}", Method.GET);
request.AddUrlSegment("id", id.ToString());
return GetFromCache<User>(request, "User" + id.ToString());
}
}
Now, when I am trying to call the GetById method in the code-behind of some ASP.NET pages, I could not see or access this method and I don't know why. Here's the line of code I am using to access the method:
string userId = "JohnA";
var user = UsersClient.GetById(userId);
So how can I access this method? or how can I use the API client over my application?
UPDATE:
I am still struggling with this API client. Could you please show me how I can use it and how I can apply dependency injection?
You cannot access non-static method like that. First you have to initialize UsersClient object.
ICacheService cache = //initialize cache here
IDeserializer deserializer = //initialize deserializer here
IErrorLogger errorLogger = //initialize errorLogger here
UsersClient usersClient = new UsersClient(cache, deserializer, errorLogger);
string userId = "JohnA";
var user = usersClient.GetById(userId);
I would recommend to learn about design patterns like dependency injection and inversion of control (already used, not sure if it was intended or unconsciously) and use them in this case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With