Search code examples
c#entity-frameworkasp.net-identitydbcontextaudit.net

Third-party implementation of DbContext, how to also implement IdentityDbContext


I'm working with Audit.NET, an open-source auditing framework, which provides an extension for Entity Framework and DbContext here: AuditDbContext.cs

// Implements DbContext public abstract partial class AuditDbContext : DbContext

I'd like to implement Audit.NET in my project using this Entity Framework extension because it would automate a lot of the steps I'd otherwise need to do manually (I'm able to use Audit.NET manually and without the Entity Framework extension). The problem I'm running into is that my solution repository implements IdentityDbContext which of course is an implementation of DbContext also.

// Implements IdentityDbContext public class MyDataContext : IdentityDbContext<ApplicationUser> { public MyDataContext() : base("DefaultConnection") { } ...

There is no existing AuditDbContext that implements IdentityDbContext.

I can't seem to think of a clean way to mix these two together and make my repository use AuditDbContext, especially given that AuditDbContext has protected constructors, and that both DbContext and IdentityDbContext have protected methods. I attempted to create a composition called AuditIdentityDbContext that had private copies of each context, but I'm not able to fulfill all of their interfaces by doing so.

It seems like all 3 DbContext types above need to be inherited from because of the protected members. For the first time in my career, I feel like multiple inheritance might actually help in this situation, but given that isn't a possibility, what would be the best alternative?

The only thing I can think of is creating a new class that inherits from either AuditDbContext or IdentityDbContext<TUser> and manually implement whatever is left to match the functionality of the other. There are no interface classes to implement though, so I'm pretty sure this isn't going to work. I feel like I must be overlooking something.


Solution

  • @trailmax solution should work, but I've updated the Audit.NET library to include support for IdentityDbContext.

    A new class AuditIdentityDbContext is provided so you can change your context to inherit from that one.

    You should change your code to:

    public class MyDataContext : AuditIdentityDbContext<ApplicationUser>
    {
        ...
    }
    

    Note: I'm the library owner

    GitHub Issue