IoC and dynamic objects

I find it difficult to figure out how to resolve objects that depend on objects that are not deterministic when 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 an instance of DocumentEditor:

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

So far I have considered two approaches, but none of them seem good:

Using factories that are being introduced

The problem with this approach is that you can create a factory for each type that 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 50 more classes and you will see the problem ...

Using nested containers

. ( Unity):

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

, .

( , , . . : , ?)

, DocumentEditorFactory, .

...

+3
4

autofac , DelegateFactories. , .

+1

AutoFac, . ContainerBuilder, . , ContainerScoped, , . , DocumentEditor , .

http://code.google.com/p/autofac/wiki/NuancesOfTracking

0

,

, factory , .

. Misko Hevery . : factory , factory .

0

MEFy: SpellChecker WordCounter , say IDocumentEditorExtension ():

IDocumentEditor editor = Registry.Resolve<IDocumentEditor>();
IDocumentEditorExtension[] extensions = Registry.ResolveAll<IDocumentEditorExtension>();

extensions.ForEach((e) => e.AttachTo(editor));
-1

Source: https://habr.com/ru/post/1707237/


All Articles