Since MvvmCross v7 sticks on its own IoC container, I would like to replace it with the .NET Core one in order to have an easier life when registering third party libraries such as IHttpClientFactory
, Polly
, Automapper
, etc. through already built-in extensions methods.
To achieve this, I've successfully created a class that implementas MvxSingleton<IMvxIoCProvider>
described as follow:
public class HostingAdapter : MvxSingleton<IMvxIoCProvider>, IMvxIoCProvider
{
private IServiceProvider ServiceProvider;
private IServiceCollection ServiceCollection;
public HostingAdapter()
{
var host = Host
.ConfigureServices((context, serviceCollection) =>
{
// Configure local services
ConfigureServices(context, serviceCollection);
ServiceCollection = serviceCollection;
ServiceProvider = ServiceCollection.BuildServiceProvider();
})
.Build();
}
public void RegisterType<TFrom, TTo>() where TFrom : class where TTo : class, TFrom
{
ServiceCollection.AddTransient<TFrom, TTo>();
ServiceProvider = ServiceCollection.BuildServiceProvider();
}
public T GetSingleton<T>() where T : class
{
return ServiceProvider.GetRequiredService<T>();
}
public object GetSingleton(Type type)
{
return ServiceProvider.GetRequiredService(type);
}
.. and all the required methods requested by the interface. Then on the platform specific side I override the IoC creation as follow:
protected override IMvxIoCProvider CreateIocProvider()
{
var hostingAdapter = new HostingAdapter();
return hostingAdapter;
}
The code seems to work but as soon as the app starts Mvx registers its own "extra" services such as the IMvxLoggerProvider
, IMvxSettings
and so on. And here issues come:
ServiceProvider = ServiceCollection.BuildServiceProvider();
is called during theHost
initialization but Mvx still continue to register services after that. This means IServiceProvider is not 'in sync' with IServiceCollection and a newServiceCollection.BuildServiceProvider();
call is needed. I temporarily solved updating the provider at each collection registration (like the code above) but I'm aware this affects performances. Anyone knows how to workaround this?There are plenty of Mvx services that are not registered so the app fails to start. These are the
IMvxLogProvider
,IMvxAndroidLifetimeMonitor
,IIMvxSettings
,IMvxStart
, etc. I just wonder, why? How can let Mvx handle the registration in my container of all what it needs to start? I partially solved some of them such as the logger thing replacing the default with a custom one, but other callbacks likeInitializeLifetimeMonitor
are called too late for being registered.Do I need to change anything in my
MvxApplication
than the most standard implementation?Am I really forced to replace the standard IoC container? How can I handle the
IServiceCollection
's extension methods that 3rd party libraries expose likeservices.AddHttpClient();
?
If it needs, I am on Xamarin classic using the Droid platform. Thanks