Skip to content

Instantly share code, notes, and snippets.

@PulkitSethi1984
Created May 15, 2018 01:38
Show Gist options
  • Save PulkitSethi1984/a8bb7f379f584aaf59c658ecafb795e4 to your computer and use it in GitHub Desktop.
Save PulkitSethi1984/a8bb7f379f584aaf59c658ecafb795e4 to your computer and use it in GitHub Desktop.
using System;
using App.Common.Core.ViewModels;
using App.Common.Core.Services.Network;
using App.Common.Core.Services.Data;
using Autofac;
using Xamarin.Forms;
using System.Reflection;
using App.Common.Core.Services.App;
#if AUTOMATION
using App.Common.Core.Services.Mock;
#endif
namespace App.Common.Core
{
public class AppContainer
{
private static readonly Lazy<AppContainer> _appContainer = new Lazy<AppContainer>(() => new AppContainer());
private IContainer _container;
private AppContainer()
{
var builder = new ContainerBuilder();
LoadServices(builder);
LoadViewModels(builder);
_container = builder.Build();
}
public static AppContainer Instance => _appContainer.Value;
private void LoadServices(ContainerBuilder builder)
{
#if AUTOMATION
builder.RegisterType<MockNetworkService>().As<INetworkService>().SingleInstance();
#else
builder.RegisterType<NetworkService>().As<INetworkService>().SingleInstance();
#endif
builder.RegisterType<AnimeNetworkService>().As<IAnimeNetworkService>().SingleInstance();
builder.RegisterType<AnimeService>().As<IAnimeService>().SingleInstance();
builder.RegisterType<NavigationService>().As<INavigationService>().SingleInstance();
}
private void LoadViewModels(ContainerBuilder builder)
{
builder.RegisterType<BaseViewModel>();
builder.RegisterType<AllItemsViewModel>();
builder.RegisterType<SearchViewModel>();
}
public void LoadViewModel(BindableObject view)
{
var viewModel = _container.Resolve(Type.GetType($"{view.GetType().FullName.Replace(".Views.", ".ViewModels.")}Model, {view.GetType().GetTypeInfo().Assembly.FullName}"));
view.BindingContext = viewModel;
}
public T Resolve<T>()
{
return _container.Resolve<T>();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment