Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IoC and dynamic objects

I'm having trouble figuring out how to resolve objects that depend on objects that are non deterministically created at runtime. What is the best approach?

Imagine something like a word processor. For each document you open, you probably want to create a large number of objects that depend on the document object.

As an example, you want to get a hold of an instance of a DocumentEditor:

public class DocumentEditor {
    public DocumentEditor(IDocument document, 
                          ISpellChecker spellChecker, 
                          IWordCounter wordCounter) {
        ...
    }
}

So far, I have considered two approaches but neither seems like a good fit:

Using factories that get injected

The problem with this approach is that you can end up with a factory for each type you need to create. I.e.

public interface ISpellCheckerFactory {
    ISpellChecker Create(IDocument document);
}

public interface IWordCounterFactory {
    IWordCounter Create(IDocument document);
}

public class DocumentEditorFactory {
    public DocumentEditorFactory(ISpellCheckerFactory spellCheckerFactory,
                                 IWordCounterFactory wordCounterFactory) {
        ...
    }

    public DocumentEditor Create(IDocument document) {
        ...
    }
}

Add another 50 classes and you see the problem...

Using nested containers

Using nested containers removes the need to create a zillion factories. It is actually pretty compact (example using Unity):

var child = container.CreateChildContainer();
child.RegisterInstance<IDocument>(theDocument);
child.Resolve<DocumentEditor>();

The drawback of this approach is that the container leaks all over the place.

(As a side note, implementing in unity this is a bit tricky. See for instance: How to register types in the main container, but resolve in a child container?)

Hybrid approach

It should be possible to combine the two by implementing a DocumentEditorFactory that creates nested containers and uses the child container to resolve dependencies.

Analysis paralysis at its best...

like image 606
Andreas Avatar asked Aug 05 '26 08:08

Andreas


1 Answers

In autofac there is approach called DelegateFactories. It is a bit similar to your first option however removes the huge amounts of hand coding.

like image 163
Rashack Avatar answered Aug 08 '26 14:08

Rashack



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!