简体   繁体   中英

How can I pass parameters that I get from a DI container into a base class from a default empty constructor?

I am using dependency injection and I would like to open a page like this:

public class AppManagementPage : HeadingPageBase<AppManagementPageViewModel>
{
    public AppManagementPage(
        IMainThread mainThread,
        IAnalyticsService analyticsService,
        AppManagementPageViewModel appManagementPageViewModel) : base(appManagementPageViewModel, analyticsService, mainThread)
    {

But I have a problem in that with the navigation service I am using (Xamarin Forms Shell), there is no way to do anything other than open a page with a default empty constructor.

So what I would like to be able to do this another way. So far the only way I can think of is this. However this doesn't work and I think I am on the wrong track as it tells me "Use of base is not valid in this context".

Can someone suggest to me what I am doing wrong here:

public class AppManagementPage : HeadingPageBase<AppManagementPageViewModel>
{
    public AppManagementPage()
    {
        var mainThread = Startup.ServiceProvider.GetRequiredService<IMainThread>();
        var analyticsService = Startup.ServiceProvider.GetRequiredService<IAnalyticsService>();
        var appManagementPageViewModel = Startup.ServiceProvider.GetRequiredService<AppManagementPageViewModel>();
        base(appManagementPageViewModel, analyticsService, mainThread);

How can I call the page with its default empty constructor and then pass the needed parameters to base in the correct way?

Note I have checked out some other postings and they don't seem to help me in this particular case:

Can I pass arguments to a base constructor from a derived class's default constructor?

You, probably, should use "property injection". It available for "StructureMap" and for "NInject" libraries, for example ( https://structuremap.github.io/setter-injection/ & https://github.com/ninject/Ninject/wiki/Injection-Patterns ). Unfortunatelly, this method is not supported by built-in cdependency 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