0

I am thinking something like the following may work ok for injecting dbcontext via constructor to my service layer.... Does anyone out there have a better way? It seems to work however _context.EntityName etc don't show up in intellisense unless I cast the object to the actual class that inherits from dbcontext.

 public interface IContextFactory:IDisposable
{
    DbContext Create();
}
public class ContextFactory<TContext> : IContextFactory where TContext : DbContext, new()
{
    private DbContext _context;

    public DbContext Create()
    {
        _context = new TContext();
        _context.Configuration.LazyLoadingEnabled = true;

        return _context;
    }

    public void Dispose()
    {
        _context.Dispose();
    }
}
DfwForSale
  • 374
  • 2
  • 10
  • 1
    Here's a better idea: ditch the context factory and just inject the `DbContext` into constructors. – Steven Sep 17 '13 at 18:38
  • Related: http://stackoverflow.com/questions/10585478/one-dbcontext-per-web-request-why – Steven Sep 17 '13 at 18:38

1 Answers1

0

As Steven mentioned in his comment, you can just inject the DbContext directly from your Composition Root. Here is an example of how this could work with SimpleInjector.

container.Register<MyDbContext>(
    () => new MyDbContext("name=MyDbContext"),
    new WebRequestLifestyle(true));

Where MyDbContext is a subclass of DbContext:

public class MyDbContext: DbContext
{
    public MyDbContext(string connectionString)
        : base(connectionString)
    {
        this.Configuration.LazyLoadingEnabled = true;
    }

    /* DbSets<SomeEntity> etc */

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        //etc
    }
}
Facio Ratio
  • 3,373
  • 1
  • 16
  • 18