是否可以序列化代码配置的StructureMap容器​​供以后使用?

时间:2013-06-14 11:27:37

标签: c# serialization inversion-of-control ioc-container structuremap

我想编写一系列默认的StructureMap容器​​,然后如果需要自定义,我可以将它们写入StructureMap xml配置格式,从而可以重新配置和加载它们。

实质上,我正在寻找container.SaveConfigurationToXmlFile("someConfigFile.xml")。以下是代码示例。容器的构造不是有趣的部分。

Container container = new Container(config=>
{
    SmartInstance<Person> travolta = config.For<IPerson>().Use<Person>()
        .Ctor<String>().Is("John Travolta");
    SmartInstance<Person> picard = config.For<IPerson>().Add<Person>()
        .Ctor<String>().Is("Captain Picard");
    SmartInstance<Person> ragen = config.For<IPerson>().Add<Person>()
        .Ctor<String>().Is("Ronald Ragen");
    SmartInstance<Person> obama = config.For<IPerson>().Add<Person>()
        .Ctor<String>().Is("Barak Obama");
    SmartInstance<Person> adams = config.For<IPerson>().Add<Person>()
        .Ctor<String>().Is("Brian Adams");

    SmartInstance<Driver> designatedDriver = config.For<IDriver>().Use<Driver>()
        .Ctor<IPerson>().Is(travolta);

    config.For<IVehicle>().Use<Car>().Named("CoolKidsCar")
        .Ctor<IDriver>().Is(designatedDriver)
        .Ctor<IPerson>("passengerSeat").Is(picard)
        .Ctor<IPerson>("leftBackSeat").Is(ragen)
        .Ctor<IPerson>("centerBackseat").Is(obama)
        .Ctor<IPerson>("rightBackseat").Is(adams)
        .Ctor<double>("topSpeed").Is(200);
});

string fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "coolKidsContainer.xml");
container.SaveConfigurationToXmlFile(fileName); //Does not exist.
Container deserializedContainer = new Container(config => config.AddConfigurationFromXmlFile(fileName));

var defaultPerson = deserializedContainer.GetInstance<IPerson>();
var coolKidsCar = deserializedContainer.GetInstance<IVehicle>("CoolKidsCar");

这是否存在于StructureMap中?也许其他一些IoC容器可以做到吗?我还能做些什么来获得相同的功能?

0 个答案:

没有答案