How can I pass a runtime parameter as part of the dependency resolution?

前端 未结 5 1832
不知归路
不知归路 2021-01-30 10:28

I need to be able to pass a connection string into some of my service implementations. I am doing this in the constructor. The connection string is configurable by user will be

5条回答
  •  猫巷女王i
    2021-01-30 11:10

    I know this is a bit old but thought i'd give my input since there is a easier way to do this in my opinion. This doesn't cover all the cases as shown in other posts. But this is a easy way of doing it.

    public class MySingleton {
        public MySingleton(string s, int i, bool b){
            ...
        }
    }
    

    No lets create a service extention class to add easier and keep it neet

    public static class ServiceCollectionExtentions
    {
        public static IServiceCollection RegisterSingleton(this IServiceCollection services, string s, int i, bool b) =>
            services.AddSingleton(new MySingleton(s, i, b));
    }
    

    Now to call it from startup

    services.RegisterSingleton("s", 1, true);
    

提交回复
热议问题