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

前端 未结 5 2015
轻奢々
轻奢々 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条回答
  •  故里飘歌
    2020-11-21 23:16

    Any place where you need a run-time value to construct a particular dependency, Abstract Factory is the solution.

    Having Initialize methods on the interfaces smells of a Leaky Abstraction.

    In your case I would say that you should model the IMyIntf interface on how you need to use it - not how you intent to create implementations thereof. That's an implementation detail.

    Thus, the interface should simply be:

    public interface IMyIntf
    {
        string RunTimeParam { get; }
    }
    

    Now define the Abstract Factory:

    public interface IMyIntfFactory
    {
        IMyIntf Create(string runTimeParam);
    }
    

    You can now create a concrete implementation of IMyIntfFactory that creates concrete instances of IMyIntf like this one:

    public class MyIntf : IMyIntf
    {
        private readonly string runTimeParam;
    
        public MyIntf(string runTimeParam)
        {
            if(runTimeParam == null)
            {
                throw new ArgumentNullException("runTimeParam");
            }
    
            this.runTimeParam = runTimeParam;
        }
    
        public string RunTimeParam
        {
            get { return this.runTimeParam; }
        }
    }
    

    Notice how this allows us to protect the class' invariants by use of the readonly keyword. No smelly Initialize methods are necessary.

    An IMyIntfFactory implementation may be as simple as this:

    public class MyIntfFactory : IMyIntfFactory
    {
        public IMyIntf Create(string runTimeParam)
        {
            return new MyIntf(runTimeParam);
        }
    }
    

    In all your consumers where you need an IMyIntf instance, you simply take a dependency on IMyIntfFactory by requesting it through Constructor Injection.

    Any DI Container worth its salt will be able to auto-wire an IMyIntfFactory instance for you if you register it correctly.

提交回复
热议问题