简体   繁体   中英

Using Ninject to inject into a class (within ASP MVC3)

I have a feeling this should be a common requirement, but I can't work the proper way of doing it. I currently have a standard MVC3 site which is using Ninject to inject service classes (in singleton scope) from Project A into the constructor of the controllers - this is all working fine.

I have another class library - Project B - which requires classes from Project A. What I am wanting to do is inject the same singleton instance I use between in my MVC project within the Project B classes. Is this possible?

Currently in the global.asax, I have this for setting up the bindings.

private void SetupDependencyInjection()
        {
            // Create Ninject DI kernel
            IKernel kernel = new StandardKernel();

            kernel.Bind<IRepositoryA>().As<RepositoryA>().InSingletonScope();
            // A load more binding go here...

            // Tell ASP.NET MVC 3 to use our Ninject DI Container
            DependencyResolver.SetResolver(new NinjectResolver(kernel));
        }

Within my controller, I have something like

public ExampleController(IRepositoryA iRepositoryA, more params....)
        {
            this.iRepositoryA= iRepositoryA;
            var ProjectB.Class1 = new ProjectB.Class1(this.iRepositoryA);
            // more setup of params here....
        }

I have two classes in ProjectB which look like this

public class Class1
{
 public Class1(IRepositoryA iRepositoryA, more params...)
 {
  var class2 = new Class2(iRepositoryA, more params...);
 }
}

public class Class2
{
  public Class2(IRepositoryA iRepositoryA, more params...)
  {
   // Something goes here....
  }
}

What I am looking to do is instantiate a new instance of ProjectB.Class1 without having to pass iClass (plus potentially a load more) as a parameter. I believe I can expose IKernel from the global asax and then do something like iKernel.Get(). Is this the best way of doing this? The other problem I see is that the parameters injected into the controller may go down 3 or more levels, eg like example above, but contining further that just to Class2. Is it best in this instance to just keep passing the parameters down the chain?

You controller needs a Class1 instance, not an IRepositoryA , so the solution is to require a Class1 instance in your controller's constructor:

public ExampleController(Class1 class1) {
    this.class1 = class1;
}

// Let Ninject provide these dependencies!
public Class1(IRepositoryA repositoryA, Dependency2 dependency2) {
    this.repositoyA = classB;
    this.dependency2 = dependency2;
}

(And see Dependency Injection Myth: Reference Passing )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM