How to use Ninject in constructor injection of a type in an external assembly

江枫思渺然 提交于 2019-12-06 11:30:42

问题


I am loading a type from an external assembly and want to create an instance of the type. However, this type/class is setup for constructor injection by objects currently being managed/bound by Ninject. How can I use Ninject to create an instance of this type and inject any constructor dependencies?

Below is how I get this type.

Assembly myAssembly = Assembly.LoadFrom("MyAssembly.dll");
Type type = myAssembly.GetType("IMyType");

回答1:


Assuming you've created a Kernel, you should be able to create and have it resolved via:

kernel.Get(type)

.... then I read the question.... Assuming MyAssembly.dll has an implementation of IMyType, you need (in your main assembly) :-

kernel.Load( "MyAssembly.dll")

And in your dynamically loaded assembly:-

public class Module : StandardModule
{
    public override void Load()
    { 
        Bind<IMyType>().To<MyType>();
    }
}

And dont forget to see if MEF is the answer here, as you dont want to go writing reams of explicit plugin management and/or detection logic if you can help it (but if you're just doing straightforward stuff and are only doing the Assembly.LoadFrom() for the purposes of asking the question, you're probably still in Ninject's sweet spot.

Ditto, if you actually need to resolve an interface via Assembly.GetType(), you probably should be using something like dynamic to do the late binding you'll probably have to do (and before you know it you should be using a dynamic language or hosting a scriopting language)



来源:https://stackoverflow.com/questions/3673492/how-to-use-ninject-in-constructor-injection-of-a-type-in-an-external-assembly

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