加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何在Ninject中使用Provider

发布时间:2020-12-15 17:45:10 所属栏目:百科 来源:网络整理
导读:我有以下代码 public class Something { [Inject] public Configuration config {get;set;} //singleton [Inject] public ProviderWindowHandler windowsProvider { get; set; } //NOT singleton public void Search(string text) { WindowHandler handler =
我有以下代码
public class Something {
    [Inject]
    public Configuration config {get;set;} //singleton
    [Inject]
    public Provider<WindowHandler> windowsProvider { get; set; } //NOT singleton

    public void Search(string text) {
        WindowHandler handler = windowsProvider.Create(xxxxxx);
        //use the new handler that was created
    }
}

但似乎提供商采用了IContext,我放了xxxxxx.不应该使用IContext从我引导并从内核创建Something.cs时使用. Provider上的no参数Create方法在哪里??? (我来自Guice的土地观点,它将被编码如上).

所以问题是如何正确地做到这一点?

谢谢,
院长

解决方法

您似乎正在尝试将提供程序用作代码中的工厂.

Ninject术语中的提供者是一个工厂,它被赋予Ninject以创建特殊创建的对象.因此,它获取解析上下文,可用于创建不同的实例,具体取决于注入实例的位置.

public class FooProvider : Provider<IFoo>
{
    public override IFoo CreateInstance(IContext ctx)
    {
        // add here your special IFoo creation code
        return new Foo();
    }
}

kernel.Bind<IFoo>().ToProvider<FooProvider>();

你想要的是你的编码器中的工厂,它创建一个WindowHandler实例.因此,创建一个接口来创建这样的实例:

public interface IWindowHandlerFactory
{
    WindowHandler Create();
}

Bind<IWindowHandlerFactory>().ToFactory();

或者你可以注入Func< WindowHandler>没有添加配置.但在我看来,这没有什么意义.

注意:所有这些都需要Ninject.Extensions.Factory作为Nuget的预发布3.0.0-rc2.

另见:http://www.planetgeek.ch/2011/12/31/ninject-extensions-factory-introduction/

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读