1

I am trying to use the IRazorViewToStringRenderer as a dependency injection

Register the IRazorViewToStringRenderer as shown in the below code

public virtual void ConfigureContainer(ContainerBuilder builder)
        {
            builder.RegisterType<RazorViewToStringRenderer>().As<IRazorViewToStringRenderer>().SingleInstance();
            builder.AddMonashSecurityModel();
        }

IRazorViewToStringRenderer

public interface IRazorViewToStringRenderer
    {
        Task<string> RenderViewToStringAsync<TModel>(string viewName, TModel model);
    }

    public class RazorViewToStringRenderer : IRazorViewToStringRenderer
    {
        private readonly IRazorViewEngine _viewEngine;
        private readonly ITempDataProvider _tempDataProvider;
        private readonly IServiceProvider _serviceProvider;

        public RazorViewToStringRenderer(
          IRazorViewEngine viewEngine,
          ITempDataProvider tempDataProvider,
          IServiceProvider serviceProvider)
        {
            _viewEngine = viewEngine;
            _tempDataProvider = tempDataProvider;
            _serviceProvider = serviceProvider;
        }

        public async Task<string> RenderViewToStringAsync<TModel>(string viewName, TModel model)
        {
            var actionContext = GetActionContext();
            var view = FindView(actionContext, viewName);

            using (var output = new StringWriter())
            {
                var viewContext = new ViewContext(
                  actionContext,
                  view,
                  new ViewDataDictionary<TModel>(new EmptyModelMetadataProvider(), new ModelStateDictionary())
                  {
                      Model = model
                  },
                  new TempDataDictionary(actionContext.HttpContext, _tempDataProvider),
                  output,
                  new HtmlHelperOptions());

                await view.RenderAsync(viewContext);

                return output.ToString();
            }
        }

        private IView FindView(ActionContext actionContext, string viewName)
        {
            var getViewResult = _viewEngine.GetView(executingFilePath: null, viewPath: viewName, isMainPage: true);
            if (getViewResult.Success)
            {
                return getViewResult.View;
            }

            var findViewResult = _viewEngine.FindView(actionContext, viewName, isMainPage: true);
            if (findViewResult.Success)
            {
                return findViewResult.View;
            }

            var searchedLocations = getViewResult.SearchedLocations.Concat(findViewResult.SearchedLocations);
            var errorMessage = string.Join(
              Environment.NewLine,
              new[] { $"Unable to find view '{viewName}'. The following locations were searched:" }.Concat(searchedLocations));

            throw new InvalidOperationException(errorMessage);
        }

        private ActionContext GetActionContext()
        {
            var httpContext = new DefaultHttpContext { RequestServices = _serviceProvider };
            return new ActionContext(httpContext, new RouteData(), new ActionDescriptor());
        }
    }

Still, I am facing the issue with the auto fact as shown below

x-exception: DependencyResolutionException 
 x-message: None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'Monash.Identity.Api.Services.RazorViewToStringRenderer' can be invoked with the available services and parameters:Cannot resolve parameter 'Microsoft.AspNetCore.Mvc.Razor.IRazorViewEngine viewEngine' of constructor 'Void .ctor(Microsoft.AspNetCore.Mvc.Razor.IRazorViewEngine, Microsoft.AspNetCore.Mvc.ViewFeatures.ITempDataProvider, System.IServiceProvider)'. 
 x-powered-by: ASP.NET

Program.cs

public class Program {

        public const string ApplicationName = "XXXXXXX";


        public const string ResourceIdentifier = "XXXXXXX";


        public static IConfiguration Configuration { get; } = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", optional: true)
            .AddJsonFile("error-settings.json")
            .AddEnvironmentVariables()
            .Build();


        public static int Main(string[] args)
        {
            Log.Logger = Configuration
                .GetLoggerConfiguration(includeEnvironmentVariables: true)
                .CreateLogger();

            try
            {
                Log.Logger.Information("{ApplicationName} is starting up...", ApplicationName);
                BuildWebHost(args)
                    .Build()
                    .Run();

                return 0;
            }
            catch (Exception ex)
            {
                Log.Logger.Fatal(ex, "Host terminated unexpectedly");
                return 1;
            }
        }


        public static IHostBuilder BuildWebHost(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .UseServiceProviderFactory(new AutofacServiceProviderFactory())
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder
                        .UseConfiguration(Configuration)
                        .ConfigureLogging((ctx, loggingBuilder) =>
                        {
                            ctx.Configuration.ConfigureLogging(
                                loggingBuilder,
                                loggerConfig => loggerConfig
                                    .Enrich.WithProperty("SystemIdentifier", Program.ApplicationName)
                                    .Enrich.WithTraceIdentifier()
                            );
                        })
                        .ConfigureServices(x => x.AddAutofac())
                        .ConfigureAppConfiguration((context, configBuilder) =>
                        {
                            var vaultConfig = new AzureKeyVaultOptions();
                            Configuration.GetSection("AzureKeyVault").Bind(vaultConfig);

                            configBuilder.ConfigureAzureKeyVault(vaultConfig);

                        }).UseStartup<Startup>();
                });
    }

References

None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder'

None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder'

None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder'

San Jaisy
  • 15,327
  • 34
  • 171
  • 290
  • Have you registered the dependencies it needs for injection? Autofac is suggesting you have not. – Jonathon Chase Feb 19 '20 at 00:06
  • Do I need to register IRazorViewEngine, ITempDataProvider and IServiceProvider ? – San Jaisy Feb 19 '20 at 00:13
  • I have used the code from one of the GIT hub source public void ConfigureServices(IServiceCollection services) { services.AddTransient(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); } here they have not register the other why I need to register the other – San Jaisy Feb 19 '20 at 00:14
  • Autofac may not have the same default dependency registrations as the out-of-the-box DI service. Try adding `builder.RegisterType().As().SingleInstance();` and see if the error moves from complaining about being unable to resolve `IRazorViewEngine viewEngine` to the next parameter. Can you link the GitHub repo you are referring to? – Jonathon Chase Feb 19 '20 at 00:18
  • https://github.com/derekarends/dotnetcore-emailtemplateengine – San Jaisy Feb 19 '20 at 00:35
  • If I register RazorViewEngine then it is asking about the tempDataProvider. Since there is no need to register all the constructor parameter as per my understanding – San Jaisy Feb 19 '20 at 01:54
  • Can we see the Program.cs contents? – Jonathon Chase Feb 19 '20 at 02:00
  • @JonathonChase please check the program.cs file – San Jaisy Feb 19 '20 at 05:13

0 Answers0