Forum Xamarin.Forms

Renderer Creation DI extensibility

DanSiegelDanSiegel USUniversity ✭✭

Summary

Currently Custom Renderers are limited as to what we can inject into them. This leads developers into generally bad coding practices to get the services that they may require in the renderer. The goal would be to provide developers a way to override the default Renderer creation so that services could be directly injected into the renderer by the developers choice of DI container.

API Changes

This should be an opt in feature so that if the developer never directly sets the RendererFactory, Xamarin Forms can continue to activate new renderer's as it currently does.

Platform.SetRendererFactory( Func<IVisualElementRenderer, Type> rendererFactory );

Intended Use Case

public class App : Application
{
    public App( IPlatformInitializer initializer = null )
    {
        Container = new Container();
        RegisterTypes();
        initializer?.SetRendererFactory( Container );
        MainPage = new MainPage();
    }

    IContainer Container { get; }

    private void RegisterTypes()
    {
        // Register some types
        Container.Register<ILogger, AwesomeLogger>();
    }
}

public class iOSPlatformInitializer : IPlatformInitializer
{
    public void SetRendererFactory( IContainer container )
    {
        Platform.SetRendererFactory( ( rendererType ) => 
        {
            return container.Resolve( rendererType ) as IVisualElementRenderer;
        });
    }
}

public class LoggerPageRenderer : PageRenderer
{
    ILogger _logger { get; }

    public LoggerPageRenderer( ILogger logger )
    {
        _logger = logger;
    }

    // log stuff happening in the renderer
}
Tagged:

Open · Last Updated

Posts

Sign In or Register to comment.