如何在外部程序集中的类型的构造函数注入中使用 Ninject

发布于 2024-09-18 11:59:06 字数 282 浏览 4 评论 0原文

我正在从外部程序集加载类型并希望创建该类型的实例。但是,此类型/类是为当前由 Ninject 管理/绑定的对象设置的构造函数注入。如何使用 Ninject 创建此类型的实例并注入任何构造函数依赖项?

下面是我如何获得这种类型。

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

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");

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

很糊涂小朋友 2024-09-25 11:59:07

假设您已经创建了一个 Kernel,您应该能够通过以下方式创建并解决它:

kernel.Get(type)

...然后我读了问题...假设 MyAssembly.dll 有 IMyType 的实现,你需要(在你的主程序集中):-

kernel.Load( "MyAssembly.dll")

在动态加载的程序集中:-

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

不要忘记查看 MEF 是否是这里的答案,因为如果可以的话,你不想编写大量显式插件管理和/或检测逻辑帮助它(但如果你只是做简单的事情并且只是为了提出问题而执行Assembly.LoadFrom(),那么你可能仍然处于 Ninject 的最佳位置。

同上,如果您实际上需要通过 Assembly.GetType() 解析接口,您可能应该使用 dynamic 之类的东西来执行您可能必须执行的后期绑定(并且在你意识到之前你应该使用动态语言或托管脚本语言)

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)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文