conficient / BlazorTemplater

A library that generates HTML (e.g. for emails) from Razor Components
Apache License 2.0
146 stars 16 forks source link

Inject an IServiceProvider to Templater and ComponentRenderer #26

Closed PhotoAtomic closed 2 years ago

PhotoAtomic commented 2 years ago

I've implemented the ability to inject an already existing IServiceProvider in the Templater, this way it is more easy to use the same dependency injection mechanism available for the application it is still possible to add additional services to the templater that are not present in the service provider. by extension it is also possible to add multiple service providers due to the nature of the fluent interface, in this case the services added to the templater directly will be resolved first, if not resolved, the infrastructure will try the IServiceProvider (s one by one in the order they was added).

this should help the usage of BlazorTemplater in already existing applications without the need to obtain and reload all the type to resolve, basically re-creating the startup twice, the enviseged usage is the following

//serviceProvider is filled by the DI mechanism
public string MyMethod(IServiceProvider serviceProvider){
   var templater = new Templater();
   templater.AddServiceProvider(serviceProvider);
   var parameters = new Dictionary<string, object>()
            {
                { nameof(ServiceInjection.A), a },
                { nameof(ServiceInjection.B), b }
            };
   var result = templater.RenderComponent<ServiceInjection>(parameters);
   return result;
}