不幸的是,Xamarin 和 Xamarin Forms 没有提供像 Prism 这样的框架来处理 IoC 场景。不过,有几种方法可以解决这个问题。
首先,容器是后台服务中 PrismApplication 上的公共属性,您可以执行以下操作:
public class FooBackgroundService
{
private App _app => (App)Xamarin.Forms.Application.Current;
private void DoFoo()
{
var sqlite = _app.Container.Resolve<ISQLite>();
}
}
另一种稍微复杂的方法是使用 ServiceLocator 模式。您可能会遇到类似以下内容:
public static class Locator
{
private static Func<Type, object> _resolver;
public static T ResolveService<T>() =>
(T)_resolver?.Invoke(typeof(T));
public static void SetResolver(Func<Type, object> resolver) =>
_resolver = resolver;
}
在您的应用程序中,您只需设置解析器即可。 Prism 实际上使用 ViewModel 定位器执行类似的操作,然后允许它注入 NavigationService 的正确实例。
public class App : PrismApplication
{
protected override void OnInitialized()
{
SetServiceLocator();
NavigationService.NavigateAsync("MainPage");
}
protected override void RegisterTypes()
{
// RegisterTypes
}
private void SetServiceLocator()
{
Locator.SetResolver(type => Container.Resolve(type, true));
}
}
最后,您的服务将简单地引用服务定位器,例如:
public class BarBackgroundService
{
public void DoBar()
{
var sqlite = Locator.ResolveService<ISQLite>();
// do foo
}
}