Внедрение зависимостей в фоновую службу Android MauiAndroid

Форум для тех, кто программирует под Android
Ответить Пред. темаСлед. тема
Anonymous
 Внедрение зависимостей в фоновую службу Android Maui

Сообщение Anonymous »

Я создал фоновую службу в Android Maui, как в этом вопросе: Как создать фоновую службу в .NET Maui. Все работает нормально. Но я не понимаю, как добавить службы DI в этом фоне?
Мне нужно добавить IDbContextFactory для моего основного контекста ef и IServiceScopeFactory.
Если я добавлю их в конструктор , у меня возникла ошибка:
Error XA4213 The type 'MyBackgroundService' must provide a public default constructor.
Мой backgroubdService:
[Service]
public class AndroidBackgroundService : Service, IService
{
UpdateBackgroundService _updateBackgroundService; //I need this DI service

public AndroidBackgroundService(UpdateBackgroundService updateBackgroundService) //This compile error
{
_updateBackgroundService = updateBackgroundService;
}

public AndroidBackgroundService()
{
}

public override IBinder OnBind(Intent intent)
{
throw new NotImplementedException();
}

[return: GeneratedEnum]//we catch the actions intents to know the state of the foreground service
public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
{
if (intent.Action == "START_SERVICE")
{
RegisterNotification();//Proceed to notify
Run();
}
else if (intent.Action == "STOP_SERVICE")
{
StopForeground(true);//Stop the service
StopSelfResult(startId);
}

return StartCommandResult.NotSticky;
}

public void Run()
{
_updateBackgroundService.Run();
}

//Start and Stop Intents, set the actions for the MainActivity to get the state of the foreground service
//Setting one action to start and one action to stop the foreground service
public void Start()
{
Intent startService = new Intent(Microsoft.Maui.ApplicationModel.Platform.CurrentActivity, typeof(AndroidBackgroundService));
startService.SetAction("START_SERVICE");
Microsoft.Maui.ApplicationModel.Platform.CurrentActivity.StartService(startService);
}

public void Stop()
{
Intent stopIntent = new Intent(Microsoft.Maui.ApplicationModel.Platform.CurrentActivity, this.Class);
stopIntent.SetAction("STOP_SERVICE");
Microsoft.Maui.ApplicationModel.Platform.CurrentActivity.StartService(stopIntent);
}

private void RegisterNotification()
{
NotificationChannel channel = new NotificationChannel("ServiceChannel", "ServiceDemo", NotificationImportance.Max);
NotificationManager manager = (NotificationManager)Microsoft.Maui.ApplicationModel.Platform.CurrentActivity.GetSystemService(Context.NotificationService);
manager.CreateNotificationChannel(channel);
Notification notification = new Notification.Builder(this, "ServiceChannel")
.SetContentTitle("Агент 2 фоновый процесс запущен")
.SetSmallIcon(Resource.Drawable.abc_ab_share_pack_mtrl_alpha)
.SetOngoing(true)
.Build();

StartForeground(100, notification);
}
}

Моя служба UpdateBackgroundService
public class UpdateBackgroundService : BaseBackgroundService
{
private readonly IServiceScopeFactory scopeFactory;
private readonly IDbContextFactory _DbContextFactoryAsterix;
private readonly IDbContextFactory _DbContextFactory;

public UpdateBackgroundService(IServiceScopeFactory scopeFactory, IDbContextFactory dbContextFactory, IDbContextFactory dbContextFactoryAsterix)
: base(dbContextFactory)
{
this.scopeFactory = scopeFactory;
_DbContextFactoryAsterix = dbContextFactoryAsterix;
_DbContextFactory = dbContextFactory;
}

public Run()
{
...
}
}

Программа Мауи
builder.Services.AddTransient();
#if ANDROID
builder.Services.AddTransient();
#endif


Подробнее здесь: https://stackoverflow.com/questions/758 ... droid-maui
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение
  • Внедрение зависимостей в фоновую службу Android Maui
    Anonymous » » в форуме C#
    0 Ответы
    36 Просмотры
    Последнее сообщение Anonymous
  • Внедрение зависимостей: внедрение IEnumerable> универсальных интерфейсов.
    Anonymous » » в форуме C#
    0 Ответы
    36 Просмотры
    Последнее сообщение Anonymous
  • Внедрение зависимостей: внедрение IEnumerable> универсальных интерфейсов.
    Anonymous » » в форуме C#
    0 Ответы
    70 Просмотры
    Последнее сообщение Anonymous
  • Внедрение зависимостей в основную рабочую службу ASP.NET
    Anonymous » » в форуме C#
    0 Ответы
    15 Просмотры
    Последнее сообщение Anonymous
  • Firebase FCM не активируется, когда приложение находится в фоновом режиме. Я хочу запустить фоновую службу для обновлени
    Anonymous » » в форуме Android
    0 Ответы
    27 Просмотры
    Последнее сообщение Anonymous

Вернуться в «Android»