I’m experimenting with data access in C#. I’m writing a class that has a Save(object o) method where it will cycle through each of the object’s properties and match them to the database using attributes.
My problem is that my class needs to get the connection string, but I want the user to supply it. I don’t want it to be limited to a config file, basically. Here’s what I thought of thus far:
- Firing an event before each connection where the user would supply the string via a custom
EventArgsclass (similar to how you can supply your own object instance to an ASP.NETObjectDataSourcevia theObjectCreatingevent) - A property in my data access class
- A combination of both, where if the event has no subscribers, it goes with the property’s value
I was just wondering what other possibilities there were and what would be the best strategy in this scenario?
An event would not be natural because your code would break if not exactly a single subscriber was present. Events are meant for use-cases where the number of subscribers does not matter to class raising the event.
Use a property or an interface (like
IConnectionProvider) to inject the connection string. The interface version lends itself well to being used with a DI container.