Простите меня, я новичок в структуре модели модель/представление. Я пытаюсь вызвать зависимость от метода (IAuthenticationService), и он возвращает значение null, и я не знаю, почему. Я попытался настроить несколько своих методов, и он все еще возвращает значение null. Буду признателен за любую оказанную помощь. Я использую .net MAUI.
Услуга, которую я сделал.
public interface IAuthenticationService
{
User User { get; set; }
Task Update(int userId, string firstName, string lastname);
}
public class AuthenticationService : IAuthenticationService
{
private IHttpService _httpService;
private NavigationManager _navigationManager;
private ILocalStorageService _localStorageService;
public User User { get; set; }
public AuthenticationService(
IHttpService httpService,
NavigationManager navigationManager,
ILocalStorageService localStorageService
) {
_httpService = httpService;
_navigationManager = navigationManager;
_localStorageService = localStorageService;
}
public async Task Update(int userId, string firstName, string lastname)
{
User = await _httpService.Put<User>($"URL{userId}", new { firstName, lastname});
var output = JsonSerializer.Serialize(User);
await SecureStorage.SetAsync("UserInfo", output);
}
}
Моя программа MauiProgram.cs
var builder = MauiApp.CreateBuilder();
builder
.UseSkiaSharp()
.UseMauiApp<App>().UseMauiCommunityToolkit()
.ConfigureFonts(fonts =>
{
fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
});
builder.Services
.AddScoped<IAuthenticationService, AuthenticationService>()
.AddScoped<IUserService, UserService>()
.AddScoped<IHttpService, HttpService>()
.AddScoped<ILocalStorageService, LocalStorageService>();
builder.Services.AddScoped(x => {
var apirl = new Uri("URL");
return new HttpClient() { BaseAddress = apiUrl };
});
builder.Services.AddMauiBlazorWebView();
#if DEBUG
builder.Services.AddBlazorWebViewDeveloperTools();
#endif
builder.Services.AddSingleton<WeatherForecastService>();
return builder.Build();
Где я пытаюсь это назвать.
public partial class ProfileInformation : ContentPage
{
IAuthenticationService AuthenticationService;
private User user = new User();
public ProfileInformation()
{
InitializeComponent();
}
async void Button2_Clicked(object sender, EventArgs e)
{
int id = "1"
string namef = "test"
string namel = "test"
var test = AuthenticationService.Update(id, namef, namel);
}
Приведенная выше строка var test, служба аутентификации возвращает null.
Я попытался создать ViewModel с той же структурой, но все равно не получается. Я в растерянности и не могу найти, где я ошибся, я прочитал несколько статей и попробовал то, что они упоминали, и он все еще возвращает ноль. Я точно знаю, что это что-то на моей стороне. Я просто не могу найти, почему.
вам нужно включить параметр в свой конструктор
IAuthenticationService AuthenticationService;
public ProfileInformation(IAuthenticationService authService)
{
InitializeComponent();
this.AuthenticationService = authService;
}
Когда я добавляю этот код в ProfileInformation(), отладчик падает при попытке инициализировать представление. Будет ли это из-за того, как устроен сервис? IAuthenticationService AuthenticationService; private User user = new User(); public ProfileInformation(IAuthenticationService authService) { InitializeComponent(); this.AuthenticationService = authService; }
Он говорит Void Break(), поэтому я предполагаю, что это так, поскольку он работает без параметра. Имеет ли значение, что представление инициализируется оболочкой?
как указывает @WBuck выше, вам также необходимо зарегистрировать свою виртуальную машину. И DI обычно применяется в конструкторе ВМ, а не на странице. См. learn.microsoft.com/en-us/dotnet/architecture/maui/…
кроме того, вы можете явно разрешать объект вместо того, чтобы полагаться на конструктор. См. раздел «Решение» документов, на которые я ссылался.
Я думаю, что вам нужно ввести свой сервис в конструктор.
public partial class ProfileInformation : ContentPage
{
IAuthenticationService AuthenticationService;
private User user = new User();
public ProfileInformation(IAuthenticationService authenticationService)
{
AuthenticationService = authenticationService;
InitializeComponent();
}
async void Button2_Clicked(object sender, EventArgs e)
{
int id = "1"
string namef = "test"
string namel = "test"
var test = AuthenticationService.Update(id, namef, namel);
}
Я ни в коем случае не эксперт по
Maui
, но вам нужно внедритьIAuthenticationService
вctor
модели представленияProfileInformation
. Я считаю, что для того, чтобы это работало, вам также необходимо зарегистрироватьсяProfileInformation
в контейнере DI.