shabhari nath
shabhari nath

Reputation: 45

Non controller class not able to access DbContext

I want to access my DbContext object using dependency injection in non controller classes.

I have a ShoppingCart Controller and a Shopping cart class as below. In controller class I'm successfully getting injected DbContext but not in ShoppingCart class. So, I'm explicitly passing _context object from controller.

But when I want to use ShoppingCart directly i.e., without controller passing object. I'm getting ObjectDescoped exception.

ShoppingCartController.cs:

  public class ShoppingCartController : Controller
  {
    private readonly MrbFarmsDbContext _context;
    private ShoppingCart cart;

    public ShoppingCartController(MrbFarmsDbContext context)
    {
        _context = context;
        cart = new ShoppingCart(_context);
    }
   }

ShoppingCart.cs:

public class ShoppingCart
{
    private MrbFarmsDbContext _context;       
    public ShoppingCart(MrbFarmsDbContext context)//this constructer is called from Controller class.
    {            
        _context = context;
    }
    public ShoppingCart()
    {

    }
  }

Method:

    public static ShoppingCart GetCart(HttpContext context)
    {
        var cart = new ShoppingCart();

        cart.ShoppingCartId = cart.GetCartId(context);

        return cart;
    }

Upvotes: 3

Views: 1078

Answers (1)

nvoigt
nvoigt

Reputation: 77294

I want to access my DbContext object using dependency injection in non controller classes.

Then inject those classes to the controller, do not let the controller create them.

Normally, you'd have

  • a ShoppingCartController (web api),
  • a ShoppingCartService (business logic)
  • a ShoppingCart (plain old CLR object, data holder, no logic)

The controller should get the service injected. The controller has no idea there even is such a thing as a "context". The service gets the context injected and does all the businesslogic. And the shopping cart is just a data holder.

Remember new is glue, if you see a new in your code and it creates something that is not a plain, dumb data holder, it's probably wrong.


Example:

public class ShoppingCartController : Controller
{
    private readonly IShoppingCartService shoppingCartService;

    public ShoppingCartController(IShoppingCartService shoppingCartService)
    {
        this.shoppingCartService = shoppingCartService;
    }
}

public class ShoppingCartService : IShoppingCartService 
{
    private readonly MrbFarmsDbContext context; 

    public ShoppingCartService(MrbFarmsDbContext context)
    {            
        this.context = context;
    }
}

Upvotes: 4

Related Questions