Ninject绑定 [英] Ninject Binding

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

问题描述

如何我的接口绑定到一个具体的类中不同的装配

How do bind my interface to a concrete class in a different assembly?

我在我的解决方案如下项目:

I have the following projects in my solution:

Foo.Data

Foo.Domain

Foo.Data
Foo.Domain

在结构图我想补充我的两个组件名称为StructureMap.config文件一个然后使用PluginFamily和可插拔的属性我接口映射到我的具体类。

In Structure Map I add my two assembly names to the StructureMap.config file and a then using the PluginFamily and Pluggable attributes map my interfaces to my concrete class'.

如何能做到同样的事情Ninject?

How can accomplish the same thing with Ninject?

推荐答案

我会做一些假设在这里。

I'll make a couple of assumptions here.


  1. 您在您的Foo.Domain项目命名为伊巴尔的接口,并有一个名为BarClass具体类在你的项目中Foo.Data

  2. 您在您的Foo.Data工程实际参考Foo.Domain项目,因为BarClass实现伊巴尔。

做Ninject最简单的事情是建立在Foo.Data一个新的类,从Ninject的StandardModule派生:

The simplest thing to do with Ninject is to create a new class in Foo.Data that derives from Ninject's StandardModule:

internal class BarModule : StandardModule {
  public override void Load() {
    Bind<IBar>()
      .To<BarClass>();
  }
}

本类,然后建立了以伊巴尔的请求绑定具体类BarClass的。这是您的XML等效

This class then establishes the binding for requests of IBar to the concrete class of BarClass. This is your XML equivalent.

下一步是创建Ninject内核(又名容器),并提供该模块(即,此配置)到它。在哪里你这样做在很大程度上取决于什么样的您正在创建的应用程序。非常笼统,你通常会配置内核在逻辑切入点或开办你的代码的部分。如果它是一个控制台或Windows桌面应用程序,这很可能是的第一件事情是在main()函数之一。

The next step is to create the Ninject kernel (aka a "container") and provide this module (i.e. this configuration) to it. Where you do this depends greatly on what kind of an application you are creating. In very general terms, you will typically configure the kernel at the logical entry point or "start-up" section of your code. If it were a console or Windows desktop application, this would likely be one of the first things that the main() function does.

中的代码将是这样的:

var modules = new IModule[] {
                              new BarModule()
                            };

var kernel = new StandardKernel(modules);



在这一点上,当你做这样的事情:

At this point, when you do something like this:

var barObj = kernel.Get<IBar>()


$ b $ :b

变量barObj引用BarClass的实例

The variable barObj references an instance of BarClass.

尽管如此,我很可能不会有你的应用程序的所有细微差别的充分理解 - 例如组件动态加载等。希望这是一些帮助呢。

All said, I could very well not have a full understanding of all the nuances of your application -- e.g. assemblies are loaded dynamically, etc. Hope this is of some help anyway.

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

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