C
C#2mo ago
Xour

Options pattern in a shared class library

Hello all, I am looking to use options pattern in a shared class library, but I am not sure how should I go about it. The project structure is something like this:
- Api_1
- Layer_1
- Layer_2
..
- Api_2
- Layer_1
- Layer_2
..
- Shared class libraries
- Class_library_1
- Class_library_2
..
- Api_1
- Layer_1
- Layer_2
..
- Api_2
- Layer_1
- Layer_2
..
- Shared class libraries
- Class_library_1
- Class_library_2
..
What I need is to somewhat use options pattern in, say, Class_library_2 (or at least have access to the configuration provider in any way), but I am unsure what would be the proper way to do this. If I register the config in the Startup.cs of the Api_1 web project, those won't be available from Api_2. Should I create the option classes and register the config in both projects? Any hints or advice? Thanks a lot!
10 Replies
Pobiega
Pobiega2mo ago
normally, you'd make an IServiceCollection extension method inside the package that needs the configuration (ie Class_lib_1) something like AddClassLib1(); if you want to access the IConfiguration, thats fine and can be done in a few ways, including passing it into that method
Xour
Xour2mo ago
So I need to register the config in both projects, right? Where do I define the option classes? Something like this? https://learn.microsoft.com/en-us/dotnet/core/extensions/options-library-authors#iconfiguration-parameter
Pobiega
Pobiega2mo ago
yep, exactly like that
Xour
Xour2mo ago
Thank you. I will attempt to follow that example, still learning 😅 One more question, that still is not clear to me: where should I define the option classes?
Unknown User
Unknown User2mo ago
Message Not Public
Sign In & Join Server To View
Pobiega
Pobiega2mo ago
you would define the option class in your library that way any other project that uses it has access to it
Unknown User
Unknown User2mo ago
Message Not Public
Sign In & Join Server To View
Xour
Xour2mo ago
Thank you both, truly appreciate it!\
Unknown User
Unknown User2mo ago
Message Not Public
Sign In & Join Server To View
Xour
Xour2mo ago
Thank you. I am looking at the code right now.