Ninject dynamic multiple constructor arguments

耗尽温柔 提交于 2019-12-23 02:56:09

问题


I have been implementing Dependency Injection into an existing Winforms project and it has been going well so far, however I want to generalise the calling of the Forms, specifically the varying quantity of constructor parameters.

My code is as follows:

Public Shared Function GetForm(formObject As BaseObject, _
    parameters As Dictionary(Of String, Object)) As Form

        Select Case formObject.GetType()
            Case GetType(Production.Task)
                Return SMKernel.Kernel.Get(Of Forms.Production.Domain.ManageTask) _
                    (New Parameters.ConstructorArgument() _
                    {New Parameters.ConstructorArgument("task", _
                        CType(formObject, Production.RequiredTask))})
        End Select

    End Function

This works fine, the interface(s) are injected correctly, the constructor parameter "task" is populated and the Form works as expected.

As you can see I have a Dictionary that can contain several parameters which I need to add to the ConstructorArgument part of the Get method. Looking at the IntelliSense, I should be able to pass in an array of ConstructorArgument objects, however no matter what I have tried, it doesn't seem to work for one reason or another.

How do you accomplish this in Ninject if it is at all possible. If this way isn't possible, how can you pass multiple parameters into a Form's constructor via Ninject?


回答1:


Use the already provided ResolutionExtensions

    public static T Get<T>(this IResolutionRoot root, params IParameter[] parameters)

Then combine it with LINQ

Kernel.Get(parameters.Select(kvp => new ConstructorArgument(kvp.Key, kvp.Value)).ToArray())

Provide more details and we might give you are more elegant approach.



来源:https://stackoverflow.com/questions/14164443/ninject-dynamic-multiple-constructor-arguments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!