Convert Non static class object to static - c#

I want to get the list of Module R by using static method.
I have tried many other answer but my problem not solved
.Net Core 6
public class UnitOfWork : IUnitOfWork
{
private readonly ApplicationDbContext _DbContext;
private readonly IWebHostEnvironment _environment;
public ModuleR ModuleR { get; set; }
public UnitOfWork(ApplicationDbContext context, IWebHostEnvironment environment)
{
_DbContext = context;
_environment = environment;
ModuleR = new ModuleR(_DbContext);
}
public async Task Commit()
{
await _DbContext.SaveChangesAsync();
}
public static IEnumerable<Module> GetModules()
{
return ModuleR.GetAllList();
// Through error
// An object reference is required for the non-static field , method or property UnitOfWork.ModuleR
}
}
public class ModuleR : GenericR<Module>, IModule
{
private readonly ApplicationDbContext _DbContext;
public ModuleR(ApplicationDbContext context) : base(context)
{
_DbContext = context;
}
public IEnumerable<Module> GetAllModuleByName(string Name)
{
throw new NotImplementedException();
}
}
public interface IModule
{
IEnumerable<Module> GetAllModuleByName(string Name);
}
public interface IUnitOfWork : IDisposable
{
Task Commit();
}
// Programe.cs
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using PMS.Contracts;
using PMS.Data;
using PMS.Implementation;
//ExpandoObject object.net core
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(connectionString));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();
builder.Services.AddScoped(typeof(IUnitOfWork), typeof(UnitOfWork));
builder.Services.AddScoped(typeof(IRepository<>), typeof(GenericR<>));
builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true).AddEntityFrameworkStores<ApplicationDbContext>();
//https://learn.microsoft.com/en-us/aspnet/core/security/authorization/roles?view=aspnetcore-7.0#add-role-services-to-identity
//builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true).AddEntityFrameworkStores<ApplicationDbContext>().AddRoles<IdentityRole>();
builder.Services.AddControllersWithViews();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseMigrationsEndPoint();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.MapRazorPages();
app.Run();
Try : Is there a way to call a non-static method from a static method?
I want to get the list ModuleR with static method.
if i create new constructor then ModuleR Remains Null

Related

Autofac Dependency Injection - Data Not Saving to Database

I am trying to implement Dependency Injection with Autofac. I'm trying to add a WebAPI interface to an MVC application. My goal is to create an application that communicates via API while creating an administration panel. I don't get any error message but data is not saved in database. I think it has something to do with the Register<EFUnitOfWork> or the Register<DbContext> field.
Business Layer -> AutofacBusinessModule
public class AutofacBusinessModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<ArticleManager>().As<IArticleService>();
builder.RegisterType<EfArticleDal>().As<IArticleDal>();
builder.RegisterType<CategoryManager>().As<ICategoryService>();
builder.RegisterType<EfCategoryDal>().As<ICategoryDal>();
builder.RegisterType<CommentManager>().As<ICommentService>();
builder.RegisterType<EfCommentDal>().As<ICommentDal>();
builder.RegisterType<RoleManager>().As<IRoleService>();
builder.RegisterType<EfRoleDal>().As<IRoleDal>();
builder.RegisterType<UserManager>().As<IUserService>();
builder.RegisterType<EfUserDal>().As<IUserDal>();
builder.RegisterType<ATKlogMSSqlContext>().InstancePerLifetimeScope();
builder.RegisterType<EfUnitOfWork>().As<IUnitOfWork>().AsSelf().SingleInstance();
var assembly = System.Reflection.Assembly.GetExecutingAssembly();
builder.RegisterAssemblyTypes(assembly).AsImplementedInterfaces()
.EnableInterfaceInterceptors(new ProxyGenerationOptions()
{
Selector = new AspectInterceptorSelector()
}).SingleInstance();
}
}
Business Layer -> Article Manager
public class ArticleManager : IArticleService
{
private readonly IUnitOfWork _unitOfWork;
private readonly IMapper _mapper;
public ArticleManager(IUnitOfWork unitOfWork, IMapper mapper)
{
_unitOfWork = unitOfWork;
_mapper = mapper;
}
[ValidationAspect(typeof(ArticleAddDtoValidator))]
public async Task<IResult> Add(ArticleAddDto articleAddDto, string createdByName)
{
var mapping = _mapper.Map<Article>(articleAddDto);
mapping.CreatedByName = createdByName;
mapping.CreatedDate = DateTime.Now;
mapping.ModifiedByName = createdByName;
mapping.ModifiedDate = DateTime.Now;
mapping.Slug = SlugifyHelper.ConvertSlug(articleAddDto.Title);
mapping.UserId = 1;
await _unitOfWork.Articles.AddAsync(mapping);
await _unitOfWork.SaveAsync();
return new SuccessResult(String.Format(Messages.Article.ArticleAdded, articleAddDto.Title));
}
}
DataAccess Layer -> EFUnitOfWork
public class EfUnitOfWork : IUnitOfWork
{
private readonly ATKlogMSSqlContext _context;
private EfArticleDal _efArticleDal;
private EfCategoryDal _efCategoryDal;
private EfCommentDal _efCommentDal;
private EfRoleDal _efRoleDal;
private EfUserDal _efUserDal;
public EfUnitOfWork(ATKlogMSSqlContext context)
{
_context = context;
}
public async ValueTask DisposeAsync()
{
await _context.DisposeAsync();
}
public IArticleDal Articles => _efArticleDal ?? new EfArticleDal();
public ICategoryDal Categories => _efCategoryDal ?? new EfCategoryDal();
public ICommentDal Comments => _efCommentDal ?? new EfCommentDal();
public IRoleDal Roles => _efRoleDal ?? new EfRoleDal();
public IUserDal Users => _efUserDal ?? new EfUserDal();
public async Task<int> SaveAsync()
{
return await _context.SaveChangesAsync();
}
}
MVC -> Startup
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews().AddRazorRuntimeCompilation().AddNewtonsoftJson(opt => opt.SerializerSettings.ReferenceLoopHandling =
Newtonsoft.Json.ReferenceLoopHandling.Ignore);
services.AddAutoMapper(typeof(ArticleProfile), typeof(CategoryProfile), typeof(CommentProfile), typeof(UserProfile));
}
// 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.UseStatusCodePages();
}
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapAreaControllerRoute(
name: "Admin",
areaName: "Admin",
pattern: "Admin/{controller=Home}/{action=Index}/{id?}"
);
endpoints.MapDefaultControllerRoute();
endpoints.MapControllers();
});
}
}
MVC Layer -> Program
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureContainer<ContainerBuilder>(builder =>
{
builder.RegisterModule(new AutofacBusinessModule());
})
.ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });
}

Unable to resolve service for ApplicationDbContext while attempting to activate <projectdirectory>.Areas.Identity.Data.ApplicationDbContext

I am new to dotnet core and following through a course. Using visual studio on mac. I had some hard times to use scaffolding functionality. now I figured one mistake. fixed it. and it gives me another warning.
Output for Error:
Unable to resolve service for type
'Microsoft.EntityFrameworkCore.DbContextOptions`1[leave_management.Areas.Identity.Data.ApplicationDbContext]'
while attempting to activate
'leave_management.Areas.Identity.Data.ApplicationDbContext'.
Regular ApplicationDbContext file includes following code:
namespace leave_management.Data
{
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<Employee> Employees { get; set; }
public DbSet<LeaveRequest> LeaveRequests { get; set; }
public DbSet<LeaveType> LeaveTypes { get; set; }
public DbSet<LeaveAllocation> LeaveAllocations { get; set; }
}
}
i am using entity framework, so the inherited ApplicationDbcontext includes following:
namespace leave_management.Areas.Identity.Data
{
public class ApplicationDbContext : IdentityDbContext<Employee>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Customize the ASP.NET Identity model and override the defaults if needed.
// For example, you can rename the ASP.NET Identity table names and more.
// Add your customizations after calling base.OnModelCreating(builder);
}
}
}
The Program.cs includes following:
namespace leave_management
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
namespace leave_management
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlite(
Configuration.GetConnectionString("DefaultConnection")));
// Adding references for Repository and Contracts to Startup file
services.AddScoped<ILeaveTypeRepository, LeaveTypeRepository>();
services.AddScoped<ILeaveRequestRepository, LeaveRequestRepository>();
services.AddScoped<ILeaveAllocationRepository, LeaveAllocationRepository>();
services.AddAutoMapper(typeof(Maps));
services.AddDefaultIdentity<Employee>()
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>() ;
services.AddControllersWithViews();
services.AddRazorPages();
services.AddRazorPages().AddRazorRuntimeCompilation();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(
IApplicationBuilder app,
IWebHostEnvironment env,
UserManager<Employee> userManager,
RoleManager<IdentityRole> roleManager
)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
//app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
SeedData.Seed(userManager, roleManager);
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
}
}
}
Note: I have seen a post similar to this one, it was not pretty similar problem, I had hard times to follow the documentation. That is why I am posting here. I appreciate your help. Best regards.

HttpContext is null in ASP.Net Core 3.1?

As per https://learn.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-3.1
I've added the appropriate code for sessions in Core 3.1
Here is are my modified sections for startup.cs
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromSeconds(10);
options.Cookie.IsEssential = true;
});
services.AddControllersWithViews();
services.AddDbContext<OrderContext>(op => op.UseSqlServer(Configuration.GetConnectionString("DatabaseConn")));
services.AddDbContext<OrderContext>(op => op.UseSqlServer(Configuration.GetConnectionString("H20Connection"))); //Add
services.Configure<IISServerOptions>(options =>
{
options.AutomaticAuthentication = false;
});
}
// 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();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseSession();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
In my controller i did as follows:
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
private readonly OrderContext _dbContext;
public readonly IConfiguration _configuration;
public HomeController(ILogger<HomeController> logger, OrderContext dbContext, IConfiguration iConfig)
{
_logger = logger;
_dbContext = dbContext;
_configuration = iConfig;
if (HttpContext.Session.Get<List<Rate>>("Rates") == null)
{
HttpContext.Session.Set<List<Rate>>("Rates", GetRates());
}
}
...
But when i run this HttpContext is null.
Anyone know why is this happening?
Special thanks to #Nkosi for pointing out that HttpContext is not yet initialized in the constructor of my controller. I moved this to an action and it works now!
Thanks!

Trying to apply an authorisation filter in all my controllers but IAuthorizationHandler is not being used

I try to define an authorization policy to be applied in all methods of all my controllers. I am trying to follow the guidelines given here, in "Authorization for specific endpoints" subsection to substitute my previous AuthorizeFilter but it does not work.
In my Startup I have:
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapDefaultControllerRoute().RequireAuthorization();
});
In ConfigureServices:
services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
.AddAzureADBearer(options => this.Configuration.Bind("AzureAd", options));
services.AddAuthorization(options =>
{
options.DefaultPolicy = new AuthorizationPolicyBuilder()
.AddRequirements(new MyRequirement(MyParams))
.Build();
});
(...)
services.AddTransient<IAuthorizationHandler, MyAuthorizationHandler>();
And I have a Requirement:
public class MyRequirement : IAuthorizationRequirement
{
public EntityType MyParams { get; private set; }
public MyRequirement(MyParams myParams) { MyParams = myParams; }
}
and a Handler:
public class MyAuthorizationHandler : AuthorizationHandler<MyRequirement>
{
private readonly ILogger<MyAuthorizationHandler> logger;
private readonly IHttpContextAccessor httpContextAccessor;
public MyAuthorizationHandler(IHttpContextAccessor httpContextAccessor, ILogger<MyAuthorizationHandler> logger)
{
this.httpContextAccessor = httpContextAccessor ?? throw new ArgumentNullException(nameof(httpContextAccessor));
this.logger = logger;
}
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, MyRequirement requirement)
{
---> Some things. I don't get here when I debug.
}
}
In my controllers I do NOT put any decorator, because I want to apply this authorization policy to ALL my methods, and that's why I override the DefaultPolicy.
If I debug, I do not stop at the Handler as I expect. Actually, if I put a decorator [Authorize] in the controller, I do stop there but, as I mentioned, I'm trying to avoid having to write this decorator in all the controllers.
Why is is not working? Thank you!
My understanding is that the [Authorize] attribute is required in order to use even the default policy. What I normally do when I need to protect all my endpoints in this way is to create an abstract base controller with this attribute and then have my other controllers inherit from this.
For example:
Base controller
[Authorize]
public abstract class MyBaseController : Controller //use Controller for mvc controller or ControllerBase for api controller
{
//base controller methods and properties
}
Other controllers:
public class MyOtherController : MyBaseController
{
//controller methods and properties
}
I finally solved it. In ConfigureServices in startup:
services.AddAuthorization(options =>
{
options.AddPolicy(
"UserIsRegistered",
new AuthorizationPolicyBuilder()
.AddRequirements(new RegistrationRequirement())
.Build());
});
Then I defined the RegistrationRequirement:
public class RegistrationRequirement : IAuthorizationRequirement
{
}
Then I defined the RegistrationAuthorizationHandler
public class RegistrationAuthorizationHandler : AuthorizationHandler<RegistrationRequirement>
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, RegistrationRequirement requirement)
{
---> LOGIC I WANT TO CHECK
if (WHATEVER)
{
context.Succeed(requirement);
}
return Task.CompletedTask;
}
}
and finally in Configure in the startup again:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers().RequireAuthorization("UserIsRegistered");
});
To sum up, my main problem it was using MapDefaultControllerRoute instead of MapControllers...
Try this:
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpContextAccessor();
services.AddTransient<IAuthorizationHandler, MyAuthorizationHandler>();
services.AddControllersWithViews(config =>
{
var policy = new AuthorizationPolicyBuilder()
.AddRequirements(new MyRequirement(MyParams))
.Build();
config.Filters.Add(new AuthorizeFilter(policy));
});
services.AddDbContext<MvcProj3Context>(options =>
options.UseSqlServer(Configuration.GetConnectionString("MvcProj3Context")));
}
// 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();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseAuthentication();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}

How to inject the dbContext into iLogger

I trying to inject the ApplicationDbcontext into iLogger.
When I use _context variable inside the CustomLoggerProvider or CustomLoggerExtension it'is work.
While when the software CreateLogger create a instance of CustomLogger, I have a problem with ApplicationDbContext, when I use the _context variable to access the database the application crashes and doesn't work.
The following there is the error log:
System.ObjectDisposedException HResult=0x80131622 Messaggio=Cannot
access a disposed object. A common cause of this error is disposing a
context that was resolved from dependency injection and then later
trying to use the same context instance elsewhere in your application.
This may occur if you are calling Dispose() on the context, or
wrapping the context in a using statement. If you are using dependency
injection, you should let the dependency injection container take care
of disposing context instances.
Origine=Microsoft.EntityFrameworkCore Analisi dello stack: at
Microsoft.EntityFrameworkCore.DbContext.CheckDisposed() at
Microsoft.EntityFrameworkCore.DbContext.Add[TEntity](TEntity entity)
at Microsoft.EntityFrameworkCore.Internal.InternalDbSet1.Add(TEntity
entity) at Application.Services.EventLogDB.saveInDb(Cliente c) 28
at Application.Models.DbLogger.CustomLogger.Log[TState](LogLevel
logLevel, EventId eventId, TState state, Exception exception, Func3
formatter) in C:\Users......\Models\DbLogger\CustomLogger.cs:line 122
at
Microsoft.Extensions.Logging.Logger.g__LoggerLog|12_0[TState](LogLevel
logLevel, EventId eventId, ILogger logger, Exception exception, Func3
formatter, List1& exceptions, TState& state)
I think it's a problem of the service life cycle.
Is there anyone who knows a solution?
Startup.cs :
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddControllersWithViews();
services.AddRazorPages();
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory, IServiceProvider serviceProvider)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
var serviceHttp = serviceProvider.GetService<IHttpContextAccessor>();
var serviceDbContext = serviceProvider.GetService<GestionaleOfficinaContext>();
// THIS IS METHOD THAT SHOWS THE BAD BEHAVIOUR
// Inside logger I need of Http context service and applicationDbContext
loggerFactory.AddCustomLogger(serviceHttp, serviceDbContext);
}
}
CustomLogger.cs :
public static class CustomLoggerExtensions
{
public static ILoggerFactory AddCustomLogger(this ILoggerFactory factory, IHttpContextAccessor accessor, ApplicationDbContext_context,
Func<string, LogLevel, bool> filter = null)
{
factory.AddProvider(new CustomLogProvider(filter, accessor, _context));
return factory;
}
}
public class CustomLogProvider : ILoggerProvider
{
private readonly Func<string, LogLevel, bool> _filter;
private readonly IHttpContextAccessor _accessor;
private readonly ApplicationDbContext_context;
public CustomLogProvider(Func<string, LogLevel, bool> filter, IHttpContextAccessor accessor, ApplicationDbContext context)
{
_filter = filter;
_accessor = accessor;
_context = context;
// IF I USE THE variable _context in this place of code the applicationDbContext is available
// and so the behaviour is right
//if (_context != null)
//{
// Cliente cl = new Cliente();
// cl.codiceFiscale = "ALFA";
//
// _context.Add(cl);
// _context.SaveChanges();
//}
}
public ILogger CreateLogger(string categoryName)
{
// In this part of code there is the strange behaviour
// _context is different by null, but when I use _context
// the lifetime of service ApplicationDbContext is END
if (_context != null)
{
Cliente cl = new Cliente();
cl.codiceFiscale = "CCC";
_context.Add(cl);
_context.SaveChanges();
}
return new CustomLogger(categoryName, _filter, _accessor, _context);
}
public void Dispose()
{
//base.Dispose();
}
}
// THE ERROR IS IN THIS CLASS
public class CustomLogger : ILogger
{
private string _categoryName;
private Func<string, LogLevel, bool> _filter;
private readonly IHttpContextAccessor _accessor;
private readonly GestionaleOfficinaContext _context;
public CustomLogger(string categoryName, Func<string, LogLevel, bool> filter, IHttpContextAccessor accessor, GestionaleOfficinaContext context)
{
_categoryName = categoryName;
_filter = filter;
_accessor = accessor;
_context = context;
}
public IDisposable BeginScope<TState>(TState state)
{
return null;
}
public bool IsEnabled(LogLevel logLevel)
{
return (_filter == null || _filter(_categoryName, logLevel));
}
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
if (!IsEnabled(logLevel))
{
return;
}
if (formatter == null)
{
throw new ArgumentNullException(nameof(formatter));
}
var message = formatter(state, exception);
if (string.IsNullOrEmpty(message))
{
return;
}
message = $"{ logLevel }: {message}";
// your implementation
}
}

Categories

Resources