使用Ninject注入到类中(在ASP MVC3中)

本文关键字:ASP MVC3 使用 注入 Ninject | 更新日期: 2023-09-27 17:58:57

我觉得这应该是一个常见的需求,但我无法以正确的方式工作。我目前有一个标准的MVC3站点,它正在使用Ninject将项目a中的服务类(在singleton范围内)注入控制器的构造函数中-这一切都很好。

我有另一个类库-Project B,它需要Project A中的类。我想做的是在Project B类中注入我在MVC项目中使用的同一个singleton实例。这可能吗?

目前在global.asax中,我有这个用于设置绑定。

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

在我的控制器内,我有类似的东西

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

我在ProjectB中有两个类,看起来像这个

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

我想做的是实例化ProjectB.Class1的一个新实例,而不必将iClass(可能还有更多负载)作为参数传递。我相信我可以从全局asax中公开IKernel,然后做一些类似IKernel.Get()的事情。这是最好的方法吗?我看到的另一个问题是,注入控制器的参数可能会下降3个或更多级别,例如,像上面的例子一样,但会进一步延续到Class2。在这种情况下,保持参数向下传递是最好的吗?

使用Ninject注入到类中(在ASP MVC3中)

控制器需要Class1实例,而不是IRepositoryA,因此解决方案是在控制器的构造函数中需要Class1实例

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

(参见依赖注入神话:引用传递)