4
可能重複:
MVC3 + Ninject - How to?使用Ninject DI兩個API和MVC4 「常規」 控制器
在一個小型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;
}
這可以正常工作,但在常規控制器中執行相同操作會失敗 「沒有爲此對象定義無參數構造函數」錯誤。
任何想法?
1.如果這是該類的整個實現,爲什麼你要將'kernel'存儲在一個字段? 2.你不能讓基類實現兩個接口嗎? – MEMark