I have a controller EBisUserController which contains a public property ConnectionString obtained from appsettings.json
through dependency injection. The controller has an attribute filter 'EBisUserAuthResourceFilter' requiring use of the property ConnectionString found in the controller. What is the most performant method to access ConnectionString. I have a working example of what I want, but know this is not the correct way of doing this as it must open and read the file for each transaction.
public class EBisUserAuthResourceFilter : Attribute, IResourceFilter {
private string _connectionString;
public EBisUserAuthResourceFilter() {
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
_connectionString= builder.Build().GetValue<string>("Data:DefaultConnection:ConnectionString"); //this property exists as property of controller through DI, how can we access it?
}
}
Dependency injection is possible in filters as well.
Here is a simple way to get connection string
Now you can use this filter
You also need to add this Filter to the service collection
Another solution is to have a class representing the structure of the content of
AppSettings.json
file or a sub section and load that in your Startup classes'ConfigureServices
methodand now you can inject
IOptions<SiteSettings>
and use the needed property values. I prefer this as it is less magic strings in my code.