-1

I'm wondering what would be best practice in this scenario:

I have method which calls some other method in using statement (disposable Database Context), and that other method also needs to access Database Context, so this is option 1:

using (var db = new Database())
{
      // some code here

      //calling other function 
      var cnt = SomeFunction();
}

int SomeFunction()
{
    using (var db = new Database())
    {
      // some code here for example:
      return db.Users.Count();

    }
}

And here is option 2:

using (var db = new Database())
{
    // some code here

   //calling other function 
   var cnt = SomeFunction(db);
}

int SomeFunction(Database db)
{
   return db.Users.Count();
}

Note: Database looks smth. like this:

 public class Database : IdentityDbContext<User>
{
    public Database()
        : base("DefaultConnection", throwIfV1Schema: false)
    {
        Configuration.LazyLoadingEnabled = true;
    }


    public DbSet<IdentityUser> AspNetUsers { get; set; }
}

I would go with option 2, because there is no need for initialization of Database Context again, but I'm not sure if this is correct way of doing this.

hyperN
  • 2,674
  • 9
  • 54
  • 92
  • I would also go with option `2`, but for a better reason: You can make `SomeFunction` use an interface instead of the `Database` concrete type. – Matias Cicero Nov 09 '15 at 12:11

2 Answers2

2

DbContext instances have their own changetracker. In case you want to use a changed DbSet inside SomeFunction, use the same DbContext. If not, you can choose whatever you prefer.

blogbydev
  • 1,445
  • 2
  • 17
  • 29
1

I would go with option 3: overload your SomeFunction.

int SomeFunction()
{
  using (var db = new Database())
    return SomeFunction(db);
}

int SomeFunction(Database db)
{
  return db.Users.Count();
}

Let the caller decide whether to pass in an existing Database. Sometimes it makes sense, if the caller has one already, as in your example. Other times, the caller just has one database operation to perform, and then there is some benefit in simplifying the API by not bothering the caller with the responsibility of creating a Database and remembering to dispose of it properly.