Search code examples
c#.netentity-framework

.NET EF contextfactory share over library


I have my project where I have MyDbContext class with dbsets etc. And I have a library project where I have some utilities shared over my projects.

I would like use MyDbContext in the library, too. But for every project the dbcontext is logically another. I wanted do it over interface where will be property IDbContextFactory. But this interface needs generic type (DbContext) but it doesn't exist in the library.

I tried to find some solution but I don't know how to do it.

Thank you for your advice.

[Edit]

This is in my application

public partial class TestRepository 
{
   public TestRepository(IDbContextFactory<MyDbContext> con) 
   {
   }
}

And I would be use something like this in library. But I cannot use there MyDbContext because there doesn't exist. So I hope I will do it with interface where was reference to IDbContextFactory but I need generic type...

// Not working in library
public partial class TestRepository 
{
   public TestRepository(IDbContextFactory<MyDbContext> con) 
   {
   }
}

// Maybe works but I don't how do it
public partial class TestRepository 
{
   public TestRepository(IFrameworkDbContextFactory con) 
   {
   }
}

Solution

  • Maybe this can help you.

    In library crete interface

    public interface ISharedDbContextFactory : IDbContextFactory<DbContext> {}
    

    In project impement it

    public class SharedDbContextFactory : ISharedDbContextFactory {
       private IDbContextFactory<MyDbContext> _contextFactory;
    
       public SharedDbContextFactory(IDbContextFactory<MyDbContext> contextFactory) {
           _contextFactory = contxtFactory;
       }
    
       public MyDbContext CreateDbContext()
       {
           return _contextFactory.CreateDbContext();
       }
    }
    

    And then add it to di configuration. You can also register to di only IDbContextFactory and use it. I think it's better to have your custom interface.

    I hope I gave you some advice and didn't say anything wrong. Someone can correct me.