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'