Search code examples
c#dependency-injectionaspnetboilerplate

How to inject services into AuditingStore?


I have replaced the AuditingStore with my own so that I can set the CustomData field, and this is working great.

public class MyAuditingStore : AuditingStore
{
    public MyAuditingStore(IRepository<AuditLog, long> auditLogRepository)
        : base(auditLogRepository)
    {
    }

    public override Task SaveAsync(AuditInfo auditInfo)
    {
        auditInfo.CustomData = "certain additional data that is not captured by default";
        return base.SaveAsync(auditInfo);
    }
}

But now I want to know how to inject services into the AuditingStore so that I can retrieve other information during SaveAsync. How is this done?


Solution

  • Similar to how you would inject services elsewhere.

    public class MyAuditingStore : AuditingStore
    {
        private readonly OtherInformationService _otherInformationService;
    
        public MyAuditingStore(
            IRepository<AuditLog, long> auditLogRepository,
            OtherInformationService otherInformationService)
            : base(auditLogRepository)
        {
            _otherInformationService = otherInformationService;
        }
    
        public override Task SaveAsync(AuditInfo auditInfo)
        {
            auditInfo.CustomData = otherInformationService.GetOtherInformation();
            return base.SaveAsync(auditInfo);
        }
    }
    
    public class OtherInformationService : ITransientDependency
    {
        public string GetOtherInformation()
        {
            return "other information";
        }
    }