简体   繁体   中英

Ninject: How to bind ToMethod

i want to config my bindings.

        Bind<DbContext>().To<HangTagVerwaltungContext>();
        Bind<IUnitOfWork>()
            .ToConstructor(
                x => new UnitOfWork(true, true, x.Inject<DbContext>()));

        // Managers
        Bind<ITagManager>().To<TagManager>();

        // ViewModels
        Bind<TagEditViewModel>().ToMethod(
            context =>
            {
                IUnitOfWork unitOfWork = context.Kernel.Get<IUnitOfWork>();
                ITagManager tagManager =
                    context.Kernel.Get<ITagManager>(
                        new Parameter(@"unitOfWork", unitOfWork, false));

                return new TagEditViewModel(tagManager, 
                    context.Kernel.Get<INavigationService>(), unitOfWork);
            });

My Problem is, that everytime he is creating a new UnitOfWork for the TagManager and not use the Parameter i give him in the ToMethod method. What do i wrong?

Thx for the Help. Dennis

I think you should be using ConstructorArgument instead of Parameter . The parameter name will have to match that of the constructor.

However, why are you doing this so complicated? (DI is about making things easier for you, not more complicated.) Is it because you need the same IUnitOfWork instance for tagManager and TagEditViewModel?

If that's the case, there's other ways to achieve this. You should look into scopes. They are used to make some part of the object tree use the same instance.

For the scenario you showed you might want to try .InCallScope(), but generally for IUnitOfWork there's other things which work better in the whole application, like .InRequestScope() for web projects or some other custom scope. There's other stackoverflow questions already covering this.

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