Ninject将多个实现绑定到接口 [英] Ninject bind mulitple implementations to an interface

查看:114
本文介绍了Ninject将多个实现绑定到接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在看本教程,但还不太了解如何创建一个工厂,该工厂可以为我提供接口的单独实现.

I'm looking at this tutorial, but not quite understanding how to create a factory that can provide me separate implementations of an interface.

http://stefanoricciardi.com/2011/01 /21/ninject-mini-tutorial-part-1/

public class IJob {
  ...
}

public class JobImpl1 : IJob {
  ...
}

public class JobImpl2 : IJob {
  ...
}

using (IKernel kernel = new StandardKernel()) {
    kernel.Bind<IJob>().To<JobImpl2>(); 
    var job = kernel.Get<IJob>();
}

我的目标是创建一个包装此Ninject内核的工厂类,以便根据我处于单元测试环境还是实际环境中,为IJob接口提供不同的实现.但是,我也想将Ninject隐藏在工厂包装器中,以使其余代码不会依赖于Ninject.

My goal is to make a factory class that wraps this Ninject Kernel so I can provide different implementations of my IJob interface depending on whether I'm in a unit test environment vs a live environment. However, I also want to keep the Ninject hidden inside the factory wrapper so that the rest of the code will not depend on Ninject.

推荐答案

有一个单独的扩展名 Ninject .Extensions.Factory ,可让您基于 interface

There is a separate extension Ninject.Extensions.Factory that allows you to generate Abstract Factory implementation on fly based on interface

var kernel = new StandardKernel();

// wire concrete implementation to abstraction/interface
kernel.Bind<IJob>().To<JobImpl1>()
    .NamedLikeFactoryMethod<IJob, IJobFactory>(f => f.GetJob());

// configure IJobFactory to be Abstract Factory
// that will include kernel and act according to kernel configuration    
kernel.Bind<IJobFactory>().ToFactory();

在运行时使用内核

解析 Abstract Factory

Resolve Abstract Factory at runtime using kernel

// get an instance of Abstract Factory
var abstractFactory = kernel.Get<IJobFactory>();

// resolve dependency using Abstract Factory
var job = abstractFactory.GetJob()

抽象工厂界面

public interface IJobFactory
{
    IJobFactory GetJob();
}

这篇关于Ninject将多个实现绑定到接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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