Implementing Dependency Injection (DI) for CleanArchitecture Azure Function Project

mukesh salaria 0 Reputation points
2023-08-04T06:34:27.27+00:00

Problem: I'm working on a project based on Jason Taylor's CleanArchitecture, and I need to implement Dependency Injection (DI) for my Azure Function project. Specifically, I want to inject the ApplicationDbContext and some other services from the infrastructure layer. Code: Below is the constructor implementation for ApplicationDbContext inside the Infrastructure layer:

public ApplicationDbContext(
    ICurrentUserService currentUserService,
    IDateTime dateTime,
    IGetLocalIPAddress getLocalIPAddress,
    DbContextOptions options,
    IOptions<OperationalStoreOptions> operationalStoreOptions,
    IAzureKeyVaultService azureKeyVaultService,
    IMediator mediator,
    IConfiguration config,
    AuditableEntitySaveChangesInterceptor auditableEntitySaveChangesInterceptor)
    : base(options)
{
    // Constructor implementation
}

I have already registered this service in my Program.cs file inside the **WEBUI **project:

builder.Services.AddInfrastructureServices(builder.Configuration);

And this is the **configuration **file inside the **Infrastructure **layer:

public static IServiceCollection AddInfrastructureServices(this IServiceCollection services, IConfiguration configuration)
{
    // DbContext registration
    // ...
    services.AddScoped<AuditableEntitySaveChangesInterceptor>();
    // Other services registration
    // ...
}

And in my AzureFunction project's Program.cs file, I've done the following:

var host = new HostBuilder()
    .ConfigureFunctionsWorkerDefaults()
    .ConfigureServices(services =>
    {
        // I need help here to properly inject the required services, especially ApplicationDbContext.
        // ...
    })
    .Build();
host.Run();

Note I have already tried <a href ="https://learn.microsoft.com/en-us/azure/azure-functions/functions-dotnet-dependency-injection"> this way </a> Question: Could you please guide me on how to correctly implement Dependency Injection for the ApplicationDbContext and the other required services in my AzureFunction project based on CleanArchitecture? I'm facing some issues with the current setup. Any help is greatly appreciated! I am trying to use the services inside my **Azurefuntion ** project From Cleanarchitech project. facing issues while performing DI I wanted to use azure **Time trigger ** function to get data from Sql server database and hit 3rd party api update the record from api to database

Azure Functions
Azure Functions
An Azure service that provides an event-driven serverless compute platform.
5,911 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Q&A Assist
    2023-08-04T06:34:27.27+00:00
    AI generated content. This question contains an answer created with AI from Q&A Assist. Learn more

    To implement Dependency Injection (DI) for your Azure Function project based on CleanArchitecture, you can follow these steps:

    1. In your Azure Function project's Program.cs file, add the following code to configure the services:
    var host = new HostBuilder()
        .ConfigureFunctionsWorkerDefaults()
        .ConfigureServices(services =>
        {
            services.AddInfrastructureServices(Configuration);
        })
        .Build();
    host.Run();
    
    1. In the ConfigureServices method of your Infrastructure layer, register the required services, including the ApplicationDbContext:
    public static IServiceCollection AddInfrastructureServices(this IServiceCollection services, IConfiguration configuration)
    {
        // DbContext registration
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(configuration.GetConnectionString("DefaultConnection")));
    
        // Other services registration
        services.AddScoped<ICurrentUserService, CurrentUserService>();
        services.AddTransient<IDateTime, DateTimeService>();
        services.AddTransient<IGetLocalIPAddress, GetLocalIPAddressService>();
        services.AddTransient<IAzureKeyVaultService, AzureKeyVaultService>();
        services.AddTransient<IMediator, Mediator>();
        services.AddTransient<IEmailSender, EmailSender>();
        services.AddTransient<ISmsSender, SmsSender>();
        services.AddTransient<ITokenService, TokenService>();
        services.AddTransient<IAccountService, AccountService>();
        services.AddTransient<IAuditableEntityService, AuditableEntityService>();
        services.AddScoped<AuditableEntitySaveChangesInterceptor>();
    
        return services;
    }
    
    1. In your Azure Function class, add the ApplicationDbContext as a constructor parameter and use it as needed:
    public class MyFunction
    {
        private readonly ApplicationDbContext _dbContext;
    
        public MyFunction(ApplicationDbContext dbContext)
        {
            _dbContext = dbContext;
        }
    
        [Function("MyFunction")]
        public async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestData req,
            FunctionContext executionContext)
        {
            // Use the _dbContext as needed
            // ...
        }
    }
    

    Note that you should replace the services registration with the ones you need for your project.


    References:

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.