简体   繁体   中英

Caliburn.Micro WPF: IoC.Get Returns Null

My code looks like this:

Bootstrapper.cs

public class Bootstrapper : BootstrapperBase
{
    private SimpleContainer _container = new SimpleContainer();

    public Bootstrapper()
    {
        Initialize();
    }

    protected override void OnStartup(object sender, StartupEventArgs e)
    {
        base.OnStartup(sender, e);
        DisplayRootViewFor<ShellViewModel>();
    }

    protected override void Configure()
    {
        _container.Singleton<IEventAggregator, EventAggregator>();
        _container.Singleton<IWindowManager, WindowManager>();
        _container.RegisterPerRequest(typeof(ShellViewModel), null, typeof(ShellViewModel));   
    }

    protected override object GetInstance(Type service, string key)
    {
        return _container.GetInstance(service, key);
    }

    protected override IEnumerable<object> GetAllInstances(Type serviceType)
    {
        return _container.GetAllInstances(serviceType);
    }

    protected override void BuildUp(object instance)
    {
        _container.BuildUp(instance);
    }
}

And my ShellViewModel looks like this:

ShellViewModel.cs

public class ShellViewModel : Conductor<Screen>
{
    public ShellViewModel
    {
        var aViewModel = IoC.Get<AViewModel>();
        ActivateItem(aViewModel);
    }
}

But whenever I run the program, a blank screen is shown. When I debug it, it said that the aViewModel is null .

Is there anything wrong with the Bootstrapper ?

Based on the code provided, AViewModel is not registered with the container in the Bootstrapper so IoC does not know it exists, thus it will return null when requested to Get that type

For example

_container.RegisterPerRequest(typeof(AViewModel), null, typeof(AViewModel));

All types that need to be resolved by IoC should first be registered with the backing container.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM