在MVC4中为api和“常规”控制器使用Ninject DI

时间:2012-08-31 09:29:12

标签: asp.net-mvc-4 ninject

  

可能重复:
  MVC3 + Ninject - How to?

在一个小型的mvc 4项目中,我尝试使用ninject实现依赖注入。

到目前为止,我已经让它与api控制器一起工作了,但我对常规控制器没有任何好运。

我有一个NinjectResolver:

public class NinjectDependencyResolver : NinjectDependencyScope, IDependencyResolver
    {
        private readonly IKernel _kernel;

        public NinjectDependencyResolver(IKernel kernel)
            : base(kernel)
        {
            _kernel = kernel;
        }

        public IDependencyScope BeginScope()
        {
            return new NinjectDependencyScope(_kernel.BeginBlock());
        }

        public override void Dispose()
        {
            _kernel.Dispose();
        }
    }

和NinjectScope:

public class NinjectDependencyScope : IDependencyScope
    {
        protected IResolutionRoot ResolutionRoot;

        public NinjectDependencyScope(IResolutionRoot kernel)
        {
            ResolutionRoot = kernel;
        }

        public object GetService(Type serviceType)
        {
            var request = ResolutionRoot.CreateRequest(serviceType, null, new Parameter[0], true, true);
            return ResolutionRoot.Resolve(request).SingleOrDefault();
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            var request = ResolutionRoot.CreateRequest(serviceType, null, new Parameter[0], true, true);
            return ResolutionRoot.Resolve(request).ToList();
        }

        public void Dispose()
        {
            var disposable = (IDisposable)ResolutionRoot;
            if (disposable != null) disposable.Dispose();
            ResolutionRoot = null;
        }
    }

然后我在Global.asax中设置它:

var kernel = new StandardKernel();
            kernel.Bind(typeof(IRepository)).To(typeof(Repository));

            GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel);

然后我将存储库注入到这样的api控制器中:

private IRepository _repository;

public TestApiController(IRepository repository)
{
    _repository = repository;
}

这样可以正常工作,但在常规控制器中执行相同操作会失败 &#34;没有为此对象定义的无参数构造函数&#34;错误。

有什么想法吗?

1 个答案:

答案 0 :(得分:5)

ASP.NET MVC使用与ASP.NET WebAPi name IDependencyResolver不同的Sytem.Web.Mvc.IDependencyResolver

所以你需要为MVC控制器提供一个新的NinjectDependencyResolver实现(幸运的是MVC和WepAPi IDependencyResolver几乎有相同的成员具有相同的签名,所以它很容易实现)

public class NinjectMvcDependencyResolver : NinjectDependencyScope, 
                                            System.Web.Mvc.IDependencyResolver
{
    private readonly IKernel _kernel;

    public NinjectDependencyResolver(IKernel kernel)
        : base(kernel)
    {
        _kernel = kernel;
    }
}

然后您可以在Global.asax中注册:

DependencyResolver.SetResolver(new NinjectMvcDependencyResolver(kernel));