简体   繁体   中英

Having issues implementing calling this interface

Can't seem to wrap my head around using an interface sometimes and am stuck trying to call this. Sorry, I realize this should be simple, but the examples I am finding just aren't working.

I have:

namespace ApiConnection{
    public interface IRestApiCalls{
        Task<bool> Login(string userName, string password);
    }
}

And it's implementation

namespace ApiConnection{
    class TestRestApiService : IRestApiCalls    {
        public async Task<bool> Login(string userName, string password){
            //Do whatever
        }
    }
}

How would I call Login? I have something similar to:

namespace Bll{
    public class Bll : IBll{  //yes, I can call this interface no problem
        public Login(string userName, string password){
            //What goes here to call the IRestApiCalls.Login interface?
        }
    }
}

You do not call an interface. An interface simply defines a contract which your class must adhere to.

You would call the method just like any other:

var myService = new TestRestApiService();
myService.Login("rob", "hunter2");

However, since it's an interface, you can also write something like this:

public void LoginService(IRestApiCalls service)
{
    service.Login("rob", "hunter2");
}

Which means you don't care what class you're given, as long as they adhere to the the contract laid out in the interface IRestApiCall

Assuming that you cannot make your login method async , you could use WaitAndUnwrapException :

IRestApiCalls rest = ...
var task = rest.Login(userName, password);
var result = task.WaitAndUnwrapException();
if (!result) {
    // Login has failed
}

If you have an option of making your own Login method async , you could await the Login from the REST object instead:

IRestApiCalls rest = ...
var result = await rest.Login(userName, password).ConfigureAwait(false);
if (!result) {
    // Login has failed
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM