Home > OS >  .NET EF contextfactory share over libarary
.NET EF contextfactory share over libarary

Time:03-10

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 isn't exists. 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 work but i dont how do it
public partial class TestRepository 
{
   public TestRepository(IFrameworkDbContextFactory con) 
   {

   }
}

CodePudding user response:

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.

  • Related