0

How can I use one DbContext with multiple application?

I have a WCF application (Net TCP binding) interface and implementation works fine with the DbContext. There is a need for API from the same application and I don't want to enable Http Binding on the WCF because of configuration and I have so many contracts. so I decided to import the service into asp.net core 2 via DI it works fine but works connect to Db via DbContext always returning null.

DB Context:

public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options){}

    public AppDbContext()
    {

    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                optionsBuilder.UseSqlServer(@"Server=.\;Database=Database;Trusted_Connection=True;MultipleActiveResultSets=true");
            }           
        }
    }

Service implementation

public partial class GeneralService : IGeneralService, IDisposable
{

    protected readonly AppDbContext Db = new AppDbContext();

    public void Dispose()
    {
        Db.Dispose();
    }
}

Asp.net core Start Up

    public void ConfigureServices(IServiceCollection services)
    {

        const string connection = @"Server=.\;Database=Database;Trusted_Connection=True;MultipleActiveResultSets=true";
        services.AddDbContext<AppDbContext>(options => options.UseSqlServer(connection));  

        services.AddSingleton<IGeneralService,GeneralService>();
        services.AddMvc()
            .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver());

    }

what am I doing wrong, what can I do I really don't want to use Proxy

Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197
rilly009
  • 253
  • 2
  • 4
  • 12

1 Answers1

0

connect to Db via DbContext always returning null.

I think that might be down to the fact that you're creating the DB context directly in the service class. You can/should inject your DbContext into your service instead. Something like:

public partial class GeneralService : IGeneralService, IDisposable
{
   protected readonly AppDbContext Db;

   public GeneralService(AppDbContext db)
   {
       Db = db;
   }
   // ... etc...
}

Further, since you're providing a connection string to the db in your Startup.cs you don't need the OnConfiguring method in your db context.

Finally, services shouldn't be singletons if they're using EF. See this answer which recommends the Request scope.