Serialization of injection / dependency inversion configurations

Recently, I have been studying dependency injection methods and inversion of control methods to improve the architecture of our application environment, and I cannot find a good answer to this question. It is very likely that my terminology is confused, messed up or I'm just naive of the concept right now, so any links or clarifications will be appreciated.

Many examples of DI and IoC containers do not illustrate how the container will connect together when you have a "library" of possible "plugins" or how to "serialize" a given configuration. (From what I read about MEF, having multiple [Export] declarations for the same type will not work if your object only needs 1 [Import]). Maybe this is a different pattern, or I'm blinded by my current thinking.

Here is the code for an example link:

public abstract class Engine {
}

public class FastEngine : Engine {
}

public class MediumEngine : Engine {
}

public class SlowEngine : Engine {
}

public class Car
{
    public Car(Engine e)
    {
        engine = e;
    }

    private Engine engine;
}

This post talks about a “fine-grained context,” where two instances of the same object need different implementations of the Engine class: IoC.Resolve vs Constructor Injection

, , - ?

public class Application
{
    public void Go()
    {
        Car c1 = new Car(new FastEngine());
        Car c2 = new Car(new SlowEngine());
    }
}

XML:

<XML>
    <Cars>
        <Car name="c1" engine="FastEngine" />
        <Car name="c2" engine="SlowEngine" />
    </Cars>
</XML>
+3
3

DI XML - , , XML . XML- .

, , MEF XML. DI.

0

mef, Spring , , , (, XML ):

<objects>
  <object name="FastCar" type="MyApp.Car">
    <constructor-arg>
       <ref object="FastEngine">
    </constructor-arg>
  </object>
  <object name="SlowCar" type="MyApp.Car">
    <constructor-arg>
       <ref object="SlowEngine">
    </constructor-arg>     
  </object>
  <object name="FastEngine" type="MyApp.FastEngine"/>
  <object name="SlowEngine" type="MyApp.SlowEngine"/>
</objects>
+1

MEF ( ), [ImportMany] Engine. , XML.

public class Application
{
    [ImportMany]
    public IEnumerable<Engine> Engines { get; set; }

    public void Go()
    {
        // I'm assuming this object was composed already...

        var cars = this.Engines.Select(e => new Car(e));

        foreach(var car in cars)
        {
            // Do something with each car
        }
    }
}

, "" . .

0

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


All Articles