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

前端 未结 5 1870
不知归路
不知归路 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条回答
  •  独厮守ぢ
    2021-01-30 11:15

    Further to @Tseng's extremely helpful answer, I found I could also adapt it to use delegates:

    public delegate INestedService INestedServiceFactory(string connectionString);
    
    services.AddTransient((provider) => new INestedServiceFactory(
        (connectionString) => new NestedService(connectionString)
    ));
    

    Implemented in RootService in the same way @Tseng suggested:

    public class RootService : IRootService
    {
        public INestedService NestedService { get; set; }
    
        public RootService(INestedServiceFactory nestedServiceFactory)
        {
            NestedService = nestedServiceFactory("ConnectionStringHere");
        }
    
        public void DoSomething()
        {
            // implement
        }
    }
    

    I prefer this approach for cases where I need an instance of a factory in a class, as it means I can have a property of type INestedServiceFactory rather than Func.

提交回复
热议问题