Forum Xamarin.Forms

UWP: service assemblies

The Forms.Init method has a parameter which can be used to specify assemblies containing renderers. This parameter is very important when using 3rd party views/renderers or a complex project structure where some renderers are in different assemblies.
public static void Init(IActivatedEventArgs launchActivatedEventArgs, IEnumerable<Assembly> rendererAssemblies = null);

However currently this parameter does not work for services, so the [Dependency(Serviceclass)] attribute can only be used in the main assembly. I think this is a severe problem for PCL projects where you might want to use MVVM like platform independent services without needing to use another dependency injection service.

Posts

  • DominikWeberDominikWeber USMember
    edited February 2016

    If someone else has this issue, I fixed it with the following workaround:

    private void RegisterServices(Assembly assembly) //TODO: remove { if (assembly == null) throw new ArgumentNullException(nameof(assembly)); var registerMethod = typeof(Xamarin.Forms.DependencyService).GetMethods().Where(x => x.Name == "Register" && x.GetGenericArguments().Length == 1).First(); var attributeProperty = typeof(Xamarin.Forms.DependencyAttribute).GetProperty("Implementor", BindingFlags.Instance | BindingFlags.NonPublic); foreach (var attribute in assembly.GetCustomAttributes<Xamarin.Forms.DependencyAttribute>()) { var implementor = (Type)attributeProperty.GetValue(attribute); registerMethod.MakeGenericMethod(implementor).Invoke(null, null); } }

    Just call the RegisterServices() method somewhere around Xamarin.Forms.Forms.Init()

  • DominikWeberDominikWeber USMember

    fyi, this is fixed in XForms 2.2: https://bugzilla.xamarin.com/show_bug.cgi?id=39449

Sign In or Register to comment.