سلام استاد خسته نباشید توی قسمت 20 توی استفاده از renderView مشکل دارم توی net core 3.1 :
لطفا کمکم کنید هر چی جستجو می کنم در مورد Di میاره که رعایتش کردم کد هامم کد های خودتونه فقط توی core 3.1.4
AggregateException: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: AngularAdvanced_BackEnd.Core.Services.Interfaces.IUserService Lifetime: Scoped ImplementationType: AngularAdvanced_BackEnd.Core.Services.Implementations.UserService': Unable to resolve service for type 'Microsoft.AspNetCore.Mvc.Razor.IRazorViewEngine' while attempting to activate 'AngularAdvanced_BackEnd.Core.Utilities.Convertors.RenderViewToString'.) (Error while validating the service descriptor 'ServiceType: AngularAdvanced_BackEnd.Core.Utilities.Convertors.IViewRenderService Lifetime: Scoped ImplementationType: AngularAdvanced_BackEnd.Core.Utilities.Convertors.RenderViewToString': Unable to resolve service for type 'Microsoft.AspNetCore.Mvc.Razor.IRazorViewEngine' while attempting to activate 'AngularAdvanced_BackEnd.Core.Utilities.Convertors.RenderViewToString'.)
استاد لطفا کمک کنید از چی میتونه باشه؟
سلام دوست من
لطفا کدهای فایل Startup.cs رو به صورت کامل ارسال کنین
using AngularAdvanced_BackEnd.Infrastructure.IoC;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens;
using System.IO;
using System.Text;
namespace AngularAdvanced_BackEnd.WebApi
{
public class Startup
{
public IConfiguration Configuration { get; }
public IHostEnvironment HostEnvironment { get; }
public Startup( IConfiguration configuration, IHostEnvironment hostEnvironment )
{
Configuration = configuration;
HostEnvironment = hostEnvironment;
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices( IServiceCollection services )
{
services.AddSingleton<IConfiguration>(new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json").Build());
#region Db Context
services.AddContext(Configuration);
#endregion
#region Authentication
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(option =>
{
option.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = true,
ValidateAudience = false,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "https://localhost:44387",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("AngularAdvancedKey"))
};
});
#endregion
#region CORS
services.AddCors(options =>
{
options.AddPolicy("EnableCors", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()
.Build();
});
});
#endregion
services.AddControllers();
RegisterDependencies(services);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure( IApplicationBuilder app, IWebHostEnvironment env )
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseStaticFiles();
app.UseAuthentication();
app.UseAuthorization();
app.UseCors("EnableCors");
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
public void RegisterDependencies( IServiceCollection service )
{
DependencyContainer.RegisterDependencies(service);
}
}
}
این کد های startup.cs
---------------------------------------
این هم RegisterDependencies
public class DependencyContainer
{
public static void RegisterDependencies( IServiceCollection services )
{
//Core Dependencies
services.AddScoped<IUserService, UserService>();
services.AddScoped<ISliderService, SliderService>();
services.AddScoped<IProductService, ProductService>();
services.AddScoped<IPasswordHelper, PasswordHelper>();
services.AddScoped<IMailSender, SendEmail>();
services.AddScoped<IViewRenderService, RenderViewToString>();
//Infrastructure Data Dependencies
services.AddScoped(typeof(IGenericRepository<>), typeof(GenericRepository<>));
}
}
توی خود startup هم inject رو انجام دادم ولی باز هم نشد
.
استاد کمک لطفا🙏🙏🙏
استاد فراموش کردی منو؟!
نه دوست من فراموش نکردم اما باید در نظر داشته باشین با این اطلاعات کم کمک کردن واقعا سخته و باید فکر کنم
لطفا کدهای IViewRenderService و RenderViewToString رو بفرستین
چیزی که در پروژه خودتون هستش رو بفرستین
استاد کد های خودتونه فقط namespace عوض شده.
که namespace هم درسته
از کد های دیگه هم استفاده کردم ولی باز هم اینطوره، پیکیجه خاصی میخواد؟
استاد لطفا یه فکری به حال این عضو کانال تلگرام شوید کنید همینی که تازه اضافه شده خیلی روی اعصابه
مشکلی که برای شما برمیگردونه مربوط به پیاده سازی RenderViewToString هستش
فعلا میتونین از ارسال ایمیل بگذرین چون آموزش به Core 3 آپدیت میشه و اونجا بررسیش میکنیم
یعنی کدش توی .net core 3 فرق داره یا نحوه تنظیم . یا جای دیگه ایش هر کدوم بود بگید خودم درستش می کنم
کد که در Core 3 فرقی نکرده اما بنا به پیاده سازی سرویس ها نباید مشکلی پیش بیاد
احتمال میدم به دلیل نوع inject کردن سرویس ها در پروژتون باشه
اگر ممکنه کدهای RenderViewToString رو ارسال کنین تا فضاهای نام استفاده شده رو بررسی کنم
چشم الان ارسال میکنم
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewEngines;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Routing;
using System;
using System.IO;
using System.Threading.Tasks;
namespace AngularAdvanced_BackEnd.Core.Utilities.Convertors
{
public interface IViewRenderService
{
Task<string> RenderToStringAsync( string viewName, object model );
}
public class RenderViewToString : IViewRenderService
{
private readonly IRazorViewEngine _razorViewEngine;
private readonly ITempDataProvider _tempDataProvider;
private readonly IServiceProvider _serviceProvider;
public RenderViewToString( IRazorViewEngine razorViewEngine,
ITempDataProvider tempDataProvider,
IServiceProvider serviceProvider )
{
_razorViewEngine = razorViewEngine;
_tempDataProvider = tempDataProvider;
_serviceProvider = serviceProvider;
}
public async Task<string> RenderToStringAsync( string viewName, object model )
{
var httpContext = new DefaultHttpContext { RequestServices = _serviceProvider };
var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());
using (var sw = new StringWriter())
{
var viewResult = _razorViewEngine.FindView(actionContext, viewName, false);
if (viewResult.View == null)
{
throw new ArgumentNullException($"{viewName} does not match any available view");
}
var viewDictionary =
new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary())
{
Model = model
};
var viewContext =
new ViewContext(actionContext, viewResult.View, viewDictionary,
new TempDataDictionary(actionContext.HttpContext, _tempDataProvider), sw,
new HtmlHelperOptions());
await viewResult.View.RenderAsync(viewContext);
var t = sw;
return sw.ToString();
}
}
}
public static class RenderView
{
public static async Task<string> RenderViewAsync<TModel>( this Controller controller, string viewName,
TModel model, bool partial = false )
{
if (String.IsNullOrEmpty(viewName))
{
viewName = controller.ControllerContext.ActionDescriptor.ActionName;
}
controller.ViewData.Model = model;
using (var writer = new StringWriter())
{
IViewEngine viewEngine =
controller.HttpContext.RequestServices.GetService(typeof(ICompositeViewEngine)) as
ICompositeViewEngine;
ViewEngineResult viewResult = viewEngine.FindView(controller.ControllerContext, viewName, !partial);
if (viewResult.Success == false)
{
return $"A view with the name {viewName} could not be found";
}
ViewContext viewContext = new ViewContext(
controller.ControllerContext,
viewResult.View,
controller.ViewData,
controller.TempData,
writer,
new HtmlHelperOptions()
);
await viewResult.View.RenderAsync(viewContext);
return writer.GetStringBuilder().ToString();
}
}
}
}
بفرمایید
درون متد ConfigureServices به جای inject کردن معمولی controller ها از دستور زیر استفاده کنین:
services.AddControllers()
.AddControllersAsServices();
تست کنین و نتیجه رو بگین
خیر استاد نشد
استاد لطفا کمک کنید
باید سرچ کنم دوست من
نهایتا باید صبر کنین تا ما هم پروژه رو به core 3 منتقل کنیم
استاد چه قدر طول میکشه؟
بعد اینکه بک اند سایت به اتمام برسه وارد پلتفرم موبایل میشیم و در نهایت پروژه رو آپدیت میکنیم
آها ممنون بابت پاسخگوییتون
مشکل رو حل کردمش فقط کافیه به جای
services.AddControllers();
نوشته بشه :
services.AddControllersWithViews();
تمام