У меня проблема с внедрением зависимостей в ViewModel. Я создал CustomerViewModel, и мне нужно вставить здесь ICustomerRepository для выполнения действия Entity Framework, например, вставить пользователя в локальную базу данных.
Вопрос: Как прикрепить (внедрить) ICustomersRepository в мою модель представления для вставки / обновления ... клиентов
Вот мой CustomerViewModel.cs:
using PropertyChanged;
using System;
using System.Threading.Tasks;
using System.Windows.Input;
using Xamarin.Forms;
namespace RodoAcceptance
{
[AddINotifyPropertyChangedInterface]
public class CustomerViewModel : BaseViewModel
{
#region Private Members
private readonly ICustomersRepository _customersRepository;
#endregion
#region Constructors
/// <summary>
/// Default constructor
/// </summary>
/// <param name="customersRepository">An instance of <see cref="ICustomersRepository"/></param>
public CustomerViewModel()
{
}
#endregion
/// <summary>
/// Element ID
/// </summary>
public int Id { get; set; }
/// <summary>
/// User rules accepted
/// </summary>
public bool IsAccepted { get; set; }
/// <summary>
/// User fullname
/// </summary>
public string FullName { get; set; }
/// <summary>
/// User birthday
/// </summary>
public DateTime? Birthday { get; set; } = new DateTime(2000, 1, 1);
/// <summary>
/// Signature wrapper
/// </summary>
public byte[] Signature { get; set; }
/// <summary>
/// Customer model
/// </summary>
public Customer Customer { get; set; }
/// <summary>
/// User signature Stream
/// </summary>
public Func<Task<byte[]>> SignatureFromStream { get; set; }
/// <summary>
/// Add new customer to database
/// </summary>
public ICommand AddCustomerCommand => new Command(async () =>
{
Signature = await SignatureFromStream();
// Signature should be != null
var customer = new Customer()
{
FullName = this.FullName,
IsAccepted = this.IsAccepted,
Birthday = this.Birthday
};
if(Signature != null)
{
customer.Image = this.Signature.ToString();
}
else
{
await Application.Current.MainPage.DisplayAlert("Błąd", "Nie wszystkie pola zostały poprawnie wypełnione", "OK");
return;
}
await _customersRepository.AddCustomerAsync(customer);
});
}
}
BottomBarPage.cs MainPage наследуется от этого класса
using Xamarin.Forms;
namespace RodoAcceptance
{
public class BottomBarPage : TabbedPage
{
private bool _tabIndexSet = false;
/// <summary>
/// Default constructor
/// </summary>
public BottomBarPage()
{
}
public enum BarThemeTypes { Light, DarkWithAlpha, DarkWithoutAlpha }
public bool FixedMode { get; set; }
public BarThemeTypes BarTheme { get; set; }
public void RaiseCurrentPageChanged()
{
OnCurrentPageChanged();
}
/// <summary>
/// When the page change event is rised
/// </summary>
protected override void OnCurrentPageChanged()
{
base.OnCurrentPageChanged();
// Get current tab index
var index = Children.IndexOf(CurrentPage);
// Check if page is loaded first time
// If page is not loaded first time...
if (_tabIndexSet)
{
// Set Customers page
if (index == 0)
{
// change binding context
CurrentPage.BindingContext = new CustomerViewModel();
}
// Set Customers List page
else if (index == 1)
{
// change binding context
CurrentPage.BindingContext = new CustomersListViewModel();
}
}
// If page is loaded first time...
else
{
_tabIndexSet = true;
}
}
}
}
CustomersRepository.cs
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace RodoAcceptance
{
public class CustomersRepository : ICustomersRepository
{
/// <summary>
/// Default database context
/// </summary>
private readonly DatabaseContext _databaseContext;
/// <summary>
/// Default constructor
/// </summary>
/// <param name="databaseContext">Database context to connect</param>
public CustomersRepository(string databaseContext)
{
_databaseContext = new DatabaseContext(databaseContext);
}
public async Task<IEnumerable<Customer>> GetCustomersAsync()
{
try
{
var customers = await _databaseContext.Customers.ToListAsync();
return customers;
}
catch (Exception e)
{
return null;
}
}
public async Task<Customer> GetCustomerByIdAsync(int id)
{
try
{
var customer = await _databaseContext.Customers.FindAsync(id);
return customer;
}
catch (Exception e)
{
return null;
}
}
public async Task<bool> AddCustomerAsync(Customer customer)
{
try
{
var tracking = await _databaseContext.Customers.AddAsync(customer);
await _databaseContext.SaveChangesAsync();
var isAdded = tracking.State == EntityState.Added;
return isAdded;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return false;
}
}
public async Task<bool> UpdateCustomerAsync(Customer customer)
{
try
{
var tracking = _databaseContext.Update(customer);
await _databaseContext.SaveChangesAsync();
var isModified = tracking.State == EntityState.Modified;
return isModified;
}
catch (Exception e)
{
return false;
}
}
public async Task<bool> RemoveCustomerAsync(int id)
{
try
{
var customer = await _databaseContext.Customers.FindAsync(id);
var tracking = _databaseContext.Remove(customer);
await _databaseContext.SaveChangesAsync();
var isDeleted = tracking.State == EntityState.Deleted;
return isDeleted;
}
catch (Exception e)
{
return false;
}
}
public async Task<IEnumerable<Customer>> QueryCustomersAsync(Func<Customer, bool> predicate)
{
try
{
var customers = _databaseContext.Customers.Where(predicate);
return customers.ToList();
}
catch (Exception e)
{
return null;
}
}
}
}