Search code examples
asp.net-mvcdesign-patternsinversion-of-controlcastle-windsortemplate-method-pattern

Providing dependencies to abstract classes


I was wondering if there is some best practice to provide dependencies to Abstract components.

Lets say I have Template Method algorithm like this:

public abstract class TemplateMethod
{              
    protected abstract void StepA();
    protected abstract void StepB();
    protected abstract void StepC();

    public void Go()
    {            
        StepA();    
        StepB();      

        CommonLogic();

        StepC();
    }

    private CommonLogic() 
    {
       myDependency.DoSomething();
    }      
}

I haven't managed to inject myDependecy to the class because the abstract TemplateMethod of course is never instantiated. I've managed to provide it with Service Location but I'm sure there is better way of doing this.

Any ideas?

PS Using Castle Windsor as IoC container.


Solution

  • Just because an abstract class can't be directly instantiated doesn't mean it can't have a constructor. You may be able to use normal constructor injection with an abstract class (please test). If you can't, you can pass the dependency to the base class like this:

    public class ChildClass: TemplateMethod
    {
        public ChildClass(IMyDependencyType myDependency) : base(myDependency) {}
    }
    
    public abstract class TemplateMethod
    {
        protected IMyDependencyType myDependency;
    
        protected TemplateMethod(IMyDependencyType myDependency) 
        {
            this.myDependency = myDependency;
        }
    }