4

可能重复:
MVC3 + Ninject - 如何?

在一个小型 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;
}

这可以正常工作,但在常规控制器中执行相同操作会失败,并出现“没有为此对象定义无参数构造函数”错误。

有任何想法吗?

4

1 回答 1

5

ASP.NET MVC 使用不同于IDependencyResolverASP.NET WebAPi的方式,即Sytem.Web.Mvc.IDependencyResolver.

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

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

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

然后你可以在Global.asaxwith 中注册它:

DependencyResolver.SetResolver(new NinjectMvcDependencyResolver(kernel));
于 2012-09-02T15:23:19.717 回答