Is there a pattern for initializing objects created via a DI container

前端 未结 5 2016
轻奢々
轻奢々 2020-11-21 22:57

I am trying to get Unity to manage the creation of my objects and I want to have some initialization parameters that are not known until run-time:

At the moment the

5条回答
  •  旧时难觅i
    2020-11-21 23:14

    I think I solved it and it feels rather wholesome, so it must be half right :))

    I split IMyIntf into a "getter" and a "setter" interfaces. So:

    interface IMyIntf {
      string RunTimeParam { get; }
    }
    
    
    interface IMyIntfSetter {
      void Initialize(string runTimeParam);
      IMyIntf MyIntf {get; }
    }
    

    Then the implementation:

    class MyIntfImpl : IMyIntf, IMyIntfSetter {
      string _runTimeParam;
    
      void Initialize(string runTimeParam) {
        _runTimeParam = runTimeParam;
      }
    
      string RunTimeParam { get; }
    
      IMyIntf MyIntf {get {return this;} }
    }
    
    //Unity configuration:
    //Only the setter is mapped to the implementation.
    container.RegisterType();
    //To retrieve an instance of IMyIntf:
    //1. create the setter
    IMyIntfSetter setter = container.Resolve();
    //2. Init it
    setter.Initialize("someparam");
    //3. Use the IMyIntf accessor
    IMyIntf intf = setter.MyIntf;
    

    IMyIntfSetter.Initialize() can still be called multiple times but using bits of Service Locator paradigm we can wrap it up quite nicely so that IMyIntfSetter is almost an internal interface that is distinct from IMyIntf.

提交回复
热议问题