TinyOC使用已注册的类型和指定的类型使用构造函数注册类

本文关键字:类型 注册 构造函数 TinyOC | 更新日期: 2023-09-27 18:25:36

我想注册一个在构造函数中使用以前注册的类型的类,但它也有一个需要指定的构造函数参数。

ConnectionEngine需要使用新的BackgroundWorkerPoll(1000)创建。我该怎么做?

        FreshIOC.Container.Register<IFormsDevice, DeviceWrapper>();
        FreshIOC.Container.Register<IBluetoothQuery, BluetoothQuery>();
        FreshIOC.Container.Register<ISuperConnectionManager, SuperConnectionManager>();
        ....................
        var superConnectionManager = FreshIOC.Container.Resolve<ISuperConnectionManager>();
        var bluetoothQuery = FreshIOC.Container.Resolve<IBluetoothQuery>();
        var formsDevice = FreshIOC.Container.Resolve<IFormsDevice>();
        var connectionEngine = new ConnectionEngine(superConnectionManager,
            bluetoothQuery, new BackgroundWorkerPoll(1000), formsDevice);

TinyOC使用已注册的类型和指定的类型使用构造函数注册类

我可以这样做,但看起来很麻烦:

        FreshIOC.Container.Register<ConnectionEngine>().UsingConstructor(() => 
        new ConnectionEngine(
            FreshIOC.Container.Resolve<ISuperConnectionManager>() as ISuperConnectionManager,
            FreshIOC.Container.Resolve<IBluetoothQuery>() as IBluetoothQuery,
            new BackgroundWorkerPoll(1000), 
            FreshIOC.Container.Resolve<IFormsDevice>() as IFormsDevice));

好的-这是我能做的最好的事情:

            FreshIOC.Container.Register<IFormsDevice, DeviceWrapper>();
            FreshIOC.Container.Register<IBluetoothQuery, BluetoothQuery>();
            FreshIOC.Container.Register<ISuperConnectionManager, SuperConnectionManager>();
            FreshIOC.Container.Register<DeviceConnectionTracker>().AsSingleton();
            FreshIOC.Container.Register<MasterParameterContainer>().AsSingleton();
            FreshIOC.Container.Register<ParsingEngine>().AsSingleton();
            var connectionEngine = FreshIOC.Container.Resolve<ConnectionEngine>(
                new NamedParameterOverloads() { { "poller", new BackgroundWorkerPoll(1000) } });
            FreshIOC.Container.Register<ConnectionEngine>(connectionEngine); // register it for FreshMVVM