我正致力于从Xamarin表单访问REST Api。我通过添加
在便携式类中创建了一个接口 public interface IRestService<T>
{
void Post(T item, string resourceURL);
}
public interface IRepository
{
}
在Drod Project中,我实现了这样的界面。
[assembly:Xamarin.Forms.Dependency(typeof(RestOperationsDroid))]
namespace VLog.Droid.DependencyServices
{
public class RestOperationsDroid : IRestService<IRepository>
{
private const string BaseURL = "http://127.0.0.1/logger/v1/";
HttpClient client;
public RestOperationsDroid()
{
client = new HttpClient();
client.MaxResponseContentBufferSize = 256000;
}
public async void Post(object item, string url)
{
var uri = new Uri(string.Format(BaseURL + url));
var jsoncontent = new StringContent(JsonConvert.SerializeObject(item), Encoding.UTF8, "application/json");
HttpResponseMessage response = null;
response = await client.PostAsync(uri, jsoncontent);
if (response.IsSuccessStatusCode)
{
//Debug(@" TodoItem successfully saved.");
}
else
{
//throw new Exception("Failed to Post data");
}
}
}
}
调用Xamarin.Forms(PCL项目)
DependencyService.Get<IRestService<Log>>().Post(_logitem, "sync");
我收到错误说:
对象引用未设置为对象的实例。
此实施中出了什么问题?
答案 0 :(得分:0)
您正在尝试从IRestService<Log>
解析DependencyService
,而您的班级会实施IRestService<IRepository>
。这些是不同的类型。您应该实现一个实现IRestService<T>
所需特定类型的类。