Внедрение интерфейса в Viewmodel равно null

Мои знания о DryIoc ограничены, и я надеюсь, что кто-нибудь сможет мне помочь. В моем мобильном приложении я читаю файл json, содержащий все мои настройки.

Я хотел бы ввести только соответствующие настройки в соответствующую модель просмотра.

В основном, как внедрить мой заполненный объект/интерфейс в конструктор модели представления

Ниже приведен нодди-тест и образец, который на данный момент не работает.

Я мог бы установить свойство модели представления, но я бы хотел, чтобы интерфейс не был нулевым при вызове конструктора модели представления.

Надеюсь все ясно. ОГРОМНОЕ СПАСИБО!!

using NUnit.Framework;
using DryIoc;

namespace DryIocTests
{
    [TestFixture]
    public class TestClass
    {
        private IAppSettings appSettings;
        [OneTimeSetUp]
        public void Setup()
        {
            //pretend we have read a json file in our mobile app
             appSettings = new AppSettings
            {
                CloudSettings = new CloudSettings {TestPropertyTwo = "Two"}
            };
        }

        [Test]
        public void ThisWorksButIsNotWhatIWant()
        {
            using (var container = new Container())
            {
                container.Register<ICloudSettings, CloudSettings>();
                container.Register<ICloudSampleViewModel, CloudSampleViewModel>();

                var vm = container.Resolve<ICloudSampleViewModel>();
                //I know that setting the property like that will work
                //but I do not want to do that .I wanted to find a way that by the time the viewModel is resolved the interface got values
                vm.CloudSettings = appSettings.CloudSettings;

                Assert.IsNotNull(vm.CloudSettings);
                Assert.IsNotNull(vm.CloudSettings.TestPropertyTwo);
            }
        }
        [Test]
        public void HowDoIMakeThisToWork()
        {
            using (var container = new Container())
            {
                container.Register<ICloudSettings, CloudSettings>();
                container.Register<ICloudSampleViewModel, CloudSampleViewModel>();

                var cloudSettings = container.Resolve<ICloudSettings>();
                cloudSettings.TestPropertyTwo = appSettings.CloudSettings.TestPropertyTwo;

                container.UseInstance(typeof(ICloudSettings));

                //by now I want that myviewmodel has the injected interface ICloudSetting populated.
                var vm = container.Resolve<ICloudSampleViewModel>();

                Assert.IsNotNull(vm.CloudSettings.TestPropertyTwo);
            }
        }
    }

    public class CloudSampleViewModel :ICloudSampleViewModel
    {
        public CloudSampleViewModel(ICloudSettings cloudSettings)
        {
            CloudSettings = cloudSettings;
        }

        public ICloudSettings CloudSettings { get; set; }
    }
    public class AppSettings : IAppSettings
    {
        public CloudSettings CloudSettings { get; set; }
    }
    public class CloudSettings: ICloudSettings{public string TestPropertyTwo { get; set; }}
    public interface IAppSettings
    {
        CloudSettings CloudSettings { get; set; }
    }

    public interface ICloudSettings{string TestPropertyTwo { get; set; }}
    public interface ICloudSampleViewModel{ICloudSettings CloudSettings { get; set; }}
}

person developer9969    schedule 10.04.2018    source источник


Ответы (1)


Вот рабочий пример.

Полный код ниже. Найдите FIX!, чтобы увидеть актуальные исправления.

using System;
using DryIoc;

public class Program
{
    public static void Main()
    {
        var p = new Program();

        p.Setup();

        p.ThisWorksButIsNotWhatIWant();

        p.HowDoIMakeThisToWork();
    }

    private IAppSettings appSettings;

    public void Setup()
    {
        //pretend we have read a json file in our mobile app
        appSettings = new AppSettings
        {
            CloudSettings = new CloudSettings {TestPropertyTwo = "Two"}
        };
    }

    public void ThisWorksButIsNotWhatIWant()
    {
        using (var container = new Container())
        {
            container.Register<ICloudSettings, CloudSettings>(
                made: PropertiesAndFields.Of.Name("TestPropertyTwo", _ => appSettings.CloudSettings.TestPropertyTwo)); // FIX!

            container.Register<ICloudSampleViewModel, CloudSampleViewModel>();

            var vm = container.Resolve<ICloudSampleViewModel>();

            Console.WriteLine("vm.CloudSettings: " + vm.CloudSettings);
            Console.WriteLine("vm.CloudSettings.TestPropertyTwo: " + vm.CloudSettings.TestPropertyTwo);
        }
    }

    public void HowDoIMakeThisToWork()
    {
        using (var container = new Container())
        {
            container.Register<ICloudSettings, CloudSettings>();
            container.Register<ICloudSampleViewModel, CloudSampleViewModel>();

            var cloudSettings = container.Resolve<ICloudSettings>();
            cloudSettings.TestPropertyTwo = appSettings.CloudSettings.TestPropertyTwo;

            container.UseInstance(cloudSettings); // FIX!

            //by now I want that myviewmodel has the injected interface ICloudSetting populated.
            var vm = container.Resolve<ICloudSampleViewModel>();

            Console.WriteLine("vm.CloudSettings.TestPropertyTwo: " + vm.CloudSettings.TestPropertyTwo);
        }
    }
}

public class CloudSampleViewModel :ICloudSampleViewModel
{
    public CloudSampleViewModel(ICloudSettings cloudSettings)
    {
        CloudSettings = cloudSettings;
    }

    public ICloudSettings CloudSettings { get; set; }
}

public class AppSettings : IAppSettings
{
    public CloudSettings CloudSettings { get; set; }
}

public class CloudSettings: ICloudSettings{ public string TestPropertyTwo { get; set; }}
public interface IAppSettings
{
    CloudSettings CloudSettings { get; set; }
}

public interface ICloudSettings{string TestPropertyTwo { get; set; }}
public interface ICloudSampleViewModel{ICloudSettings CloudSettings { get; set; }}
person dadhi    schedule 10.04.2018
comment
еще раз спасибо за ваше время и код. позвольте мне переварить и вернуться к вам - person developer9969; 10.04.2018