如何使用Ninject提供程序 [英] How to use a Provider in Ninject

查看:127
本文介绍了如何使用Ninject提供程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码

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。不应该当我自举并从内核中创建Something.cs使用的IContext。哪里是不带参数创建的提供商方法? (我从吉斯土地的角度来看它的代码应该像上面来了)。

but it seems the Provider takes an IContext where I put xxxxxx. Shouldn't the IContext from when I bootstrapped and created Something.cs from the kernel be used. Where is the no parameter Create method on the Provider??? (I am coming from Guice land point of view where it would be coded like above).

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

so the question is How do I do this correctly?

感谢,
院长

推荐答案

您似乎正在尝试使用供应商在你的代码的工厂。

It seems you are trying to use a provider as a factory in your code.

在Ninject条款提供者是给Ninject创建专门创建对象的工厂。因此它得到解决上下文可用于创建根据在注入其中实例不同实例

A provider in Ninject terms is a factory that is given to Ninject to create specially created objects. Therefore it gets the resolving context which can be used to create different instances depending where the instance in injected into.

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 。因此,创建一个接口来创建这样的实例:

What you want is a factory in your coder that creates an instance of WindowHandler. Therefore create an interface to create the instance like this:

public interface IWindowHandlerFactory
{
    WindowHandler Create();
}

Bind<IWindowHandlerFactory>().ToFactory();



另外,您可以注入 Func键< WindowHandler> 不加入的结构。但这在我看来是没有意义

Alternatively you can inject Func<WindowHandler> without adding a configuration. But this is less meaningful in my opinion.

请注意:所有这些都需要Ninject.Extensions.Factory可从预发布的NuGet 3.0.0-RC2

NOTE: All this requires Ninject.Extensions.Factory available as prerelease 3.0.0-rc2 from Nuget.

又见// WWW。 planetgeek.ch/2011/12/31/ninject-extensions-factory-introduction/

See also: http://www.planetgeek.ch/2011/12/31/ninject-extensions-factory-introduction/

这篇关于如何使用Ninject提供程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆