Search code examples
c#dependency-injectionautofac

How to apply DI on methods in nested classes


I'm trying to refactor some old code in order to implement (make use of) the dependency injection pattern.

How do I correctly new up a class, inside a different class method?

Given to following minimal example:

class Select {
    List<Where> Wheres = new List<Where>();

    public Select()
    {
    }

    public Select Where(string field, string condition, object value) 
    {
        this.Wheres.Add(new Where(field, condition)); //How to resolve this?
        return this;
    }

    public object DoSomething() 
    {
        //...
    }

}

class Where {
    string _Field;
    string _Condition;
    object _value;

    public Where(string field, string condition, object value)
    {
        _Field = field;
        _Condition = condition;
        _value = value;
    }

    public object DoSomething() 
    {
        //...
    }
}

Is it best practice to call Resovle() inside the Where-Method? Or should I consider a completely different approach?


Solution

  • After googling a bit further in this topic, I found this thread on StackExchange:
    Link.

    So basically, Autofac (or many other IoC) is able to automatically implement a factory, which can be passed as a Func. The answer on StackExchange provides 3 links with code examples for Autofac, Ninject and Castle Windsor.