An Azure service that provides an event-driven serverless compute platform.
Hello henrik johansen,
Welcome to the Microsoft Q&A and thank you for posting your questions here.
I understand that you are having issues with Azure SQL Trigger while using environment variable as connection String.
Yes, the solution provided by @Anonymous effectively addresses the issue by suggesting a method to retrieve the connection string at runtime within the function, which avoids the compile-time constant requirement.
For better approach to ensures that the connection string is managed securely and can be easily tested and maintained., this is an alternative method to address the issue of using environment variables for sensitive data in SQL triggers, by using dependency injection (DI). DI allows you to manage configuration and environment variables securely, making your code more modular and testable.
Steps you will need to do to Implement Dependency Injection in C#
- Create an interface that outlines the methods your dependency will implement.
public interface ISensorDatabaseQuery
{
Task GetData();
}
- Create a class that implements this interface.
public class SensorDatabaseQuery : ISensorDatabaseQuery
{
private string _connectionString;
public SensorDatabaseQuery(string connectionString)
{
_connectionString = connectionString;
}
public async Task GetData()
{
// Implementation for fetching data
}
}
- In your
Startupclass, register the services with the dependency injection container.
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<ISensorDatabaseQuery>(provider =>
{
var connectionString = Environment.GetEnvironmentVariable("dbconnection");
return new SensorDatabaseQuery(connectionString);
});
}
}
- Modify your Azure function to accept the dependency via constructor injection.
[Function("WarningTrigger")]
public async Task Run(
[SqlTrigger("[dbo].[SensorWarnings]")] IReadOnlyList<SqlChange<Model.SensorWarning>> changes,
FunctionContext context,
ISensorDatabaseQuery query)
{
await query.GetData();
}
By doing the above, your classes are less dependent on specific implementations, making it easier to change or replace dependencies. You can easily mock dependencies for unit testing and your code is cleaner and easier to maintain.
For more detailed information, you can refer to the documentation on Dependency Injection - https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection
I hope this is helpful! Do not hesitate to let me know if you have any other questions.
Please don't forget to close up the thread here by upvoting and accept it as an answer if it is helpful.