简体   繁体   中英

Calling non-static method using DbContext from .NET Core 2.0 Controller

I've created the following helper method which uses a constructor to retrieve the DbContext.

namespace AzureSdkExamples.Helpers
{
    public class ComputeHelpers
    {
        private readonly ApplicationDbContext _dbContext;

        public ComputeHelpers(ApplicationDbContext db)
        {
            _dbContext = db;
        }

        public async Task<List<VirtualMachine>> GetClientVirtualMachines(int customerId)
        {
            var azureClient = _dbContext.CreateAzureClient(customerId);

            var virtualMachines = await azureClient.VirtualMachines.ListAsync();

            List<VirtualMachine> virtualMachineObjects = new List<VirtualMachine>();

            int vmCount = 0;

            foreach (var virtualMachine in virtualMachines)
            {
                virtualMachineObjects.Add(
                    new VirtualMachine
                    {
                        Id = vmCount,
                        VirtualMachineName = virtualMachine.ComputerName,
                        AzureVmId = virtualMachine.VMId
                    }
                );
                vmCount++;
            }


            return virtualMachineObjects;
        }
    }
}

The CreateAzureClient is essentially a db call to retrieve my personal subscriptions and tenant information from Azure. It returns an IAzure type.

I want to them call this non-static method from my Controller. I can't use a constructor on the method as this results in the following error:

InvalidOperationException: Unable to resolve service for type 'AzureSdkExamples.Helpers.ComputeHelpers' while attempting to activate 'AzureSdkExamples.Controllers.VirtualMachinesController'.

This is my controller when calling the helper method:

namespace AzureSdkExamples.Controllers
{
    [Route("api/[controller]")]
    public class VirtualMachinesController : Controller
    {
        private readonly ComputeHelpers _computeHelper;

        public VirtualMachinesController(ComputeHelpers computeHelpers)
        {
            _computeHelper = computeHelpers;
        }

        [HttpGet("{id}", Name = "GetAllVirtualMachines")]
        public async Task<JsonResult> GetAllVirtualMachines(int customerId)
        {
            var virtualMachines = await _computeHelper.GetClientVirtualMachines(customerId);

            return Json(virtualMachines);
        }
    }
}

I'm actually at a bit of a loss on what to do, mainly due to my own misunderstanding of how to appropriately chain these constructors/methods the correct way.

I'm trying to take the best approach to avoid potential memory leaks in a multi-user context.

How do I correctly call this helper method from the controller considering the use of DI in the helper?

You should register ComputeHelpers in the DI container.

You can do that in the Startup class in the ConfigureServices method, eg with AddTransient :

services.AddTransient<ComputeHelpers, ComputeHelpers>();

See the documentation for more details about the Dependency Injection in ASP.NET Core

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM