收录日期:2020/05/27 11:59:12 时间:2009-08-07 15:45:26 标签:c#,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

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'.

How can accomplish the same thing with Ninject?

I'll make a couple of assumptions here.

  1. You have an interface named IBar in your Foo.Domain project and you have a concrete class called BarClass in your Foo.Data project.
  2. You in fact reference Foo.Domain project in your Foo.Data project because BarClass implements IBar.

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>();
  }
}

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

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.

The code would like this:

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>()

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.