这是我在浏览时显示的错误消息:../ api / User
<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>
Type 'RavenReader.Web.Controllers.UserController' does not have a default constructor
</ExceptionMessage>
<ExceptionType>System.ArgumentException</ExceptionType>
<StackTrace>
at System.Linq.Expressions.Expression.New(Type type) at System.Web.Http.Internal.TypeActivator.Create[TBase](Type instanceType) at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator) at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
</StackTrace>
</Error>
我的控制器类是
public class BaseController : ApiController
{
private readonly ICookieStorageService _cookieStorageService;
public BaseController(ICookieStorageService cookieStorageService)
{
_cookieStorageService = cookieStorageService;
}
}
public class UserController : BaseController
{
private readonly RavenUserFacade _facade;
private readonly ICookieStorageService _cookieStorageService;
public UserController(ICookieStorageService cookieStorageService, RavenUserFacade facade):base(cookieStorageService)
{
_facade = facade;
}
// GET api/User
public IEnumerable<RavenUserView> Get()
{
var users = _facade.GetAllUser();
return users.RavenUsers;
}
..........................................
..........................................
}
根据http://www.peterprovost.org/blog/2012/06/19/adding-ninject-to-web-api/此博客,我按照以下方式组织了NinjectDependencyScope
班级,NinjectDependencyResolver
班级和NinjectWebCommon
:
public class NinjectDependencyScope : IDependencyScope
{
private IResolutionRoot resolver;
internal NinjectDependencyScope(IResolutionRoot resolver)
{
Contract.Assert(resolver != null);
this.resolver = resolver;
}
public void Dispose()
{
var disposable = resolver as IDisposable;
if (disposable != null)
disposable.Dispose();
resolver = null;
}
public object GetService(Type serviceType)
{
if (resolver == null)
throw new ObjectDisposedException("this", "This scope has already been disposed");
return resolver.TryGet(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType)
{
if (resolver == null)
throw new ObjectDisposedException("this", "This scope has already been disposed");
return resolver.GetAll(serviceType);
}
}
public class NinjectDependencyResolver : NinjectDependencyScope, IDependencyResolver
{
private IKernel kernel;
public NinjectDependencyResolver(IKernel kernel)
: base(kernel)
{
this.kernel = kernel;
}
public IDependencyScope BeginScope()
{
return new NinjectDependencyScope(kernel.BeginBlock());
}
}
public static class NinjectWebCommon
{
private static readonly Bootstrapper bootstrapper = new Bootstrapper();
/// <summary>
/// Starts the application
/// </summary>
public static void Start()
{
DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
bootstrapper.Initialize(CreateKernel);
}
/// <summary>
/// Stops the application.
/// </summary>
public static void Stop()
{
bootstrapper.ShutDown();
}
/// <summary>
/// Creates the kernel that will manage your application.
/// </summary>
/// <returns>The created kernel.</returns>
public static IKernel CreateKernel()
{
var kernel = new StandardKernel();
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
RegisterServices(kernel);
GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel);
return kernel;
}
/// <summary>
/// Load your modules or register your services here!
/// </summary>
/// <param name="kernel">The kernel.</param>
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<IDbFactory>().To<IDbFactory>().InSingletonScope();
kernel.Bind<IUnitOfWork>().To<EFUnitOfWork>();
kernel.Bind<IRavenUserRepository>().To<RavenUserRepository>();
kernel.Bind<IRavenUserFacade>().To<RavenUserFacade>();
kernel.Bind<ICookieStorageService>().To<CookieStorageService>();
kernel.Bind<ICacheStorage>().To<HttpContextCacheAdapter>();
}
}
我正在使用Visual Studio 2013 Ninject For MVC-3
答案 0 :(得分:0)
我发布此答案是为了帮助您找到您所面临的根本问题。这不是一个解决方案,但这就是我重现你所遇到的完全相同的错误。
首先,您应该为NinjectDependencyResolver
使用不同的实现。我已设置this gist。这背后的原因是避免了范围(特别是单身人士)的问题,你可以更多地了解here。
回到你的问题,错误在你的绑定中,某处。首先,尝试从InSingletonScope
中删除IDbFactory
。然后,尝试从控制器构造函数中删除一个依赖项,并检查它是否有效。最后,删除基类并查看它是否有效。
这些步骤只是为了指导您追踪问题。我在这里复制了你的场景,我无法面对同样的问题。我的设置是这样的:
public class BaseController : ApiController
{
protected readonly IService _service;
public BaseController(IService service)
{
_service = service;
}
}
public class ValuesController : BaseController
{
public ISomeOtherDependency Dependency { get; set; }
public ValuesController(IService service, ISomeOtherDependency dependency) : base(service)
{
Dependency = dependency;
}
// GET api/values/5
public string Get(int id)
{
return _service.CreatedAt.ToString("u");
}
}
public interface ISomeOtherDependency
{
}
public class ConcreteDependency : ISomeOtherDependency
{
}
public interface IService
{
DateTime CreatedAt { get; }
}
public class Service : IService
{
public Service()
{
CreatedAt = DateTime.Now;
}
public DateTime CreatedAt { get; private set; }
}
我的绑定:
kernel.Bind<IService>().To<Service>(); // If I comment this, I get the same exception.
kernel.Bind<ISomeOtherDependency>().To<ConcreteDependency>();
但是通过注释掉其中一个绑定,我会得到与你完全相同的错误:
ValuesController' does not have a default constructor
我希望这可以帮助您找到解决问题的正确方法。
答案 1 :(得分:0)
感谢您的回复。我按照你的每个步骤,但在这里结果相同。最后我通过属于NinjectWebCommon.cs的绑定进行调试,我在这里发现了一个问题。调试时显示以下问题: 找到源代码 未找到Bootstrapper.cs 您需要找到Bootstrapper.cs来查看当前调用堆栈帧的来源
'c:\Projects\Ninject\Ninject.Web.Common\src\Ninject.Web.Common\Bootstrapper.cs'. Checksum: MD5 {13 3e b1 f3 ba a7 65 14 f6 dc 4d f1 dd aa 21 bf}
The file 'c:\Projects\Ninject\Ninject.Web.Common\src\Ninject.Web.Common\Bootstrapper.cs' does not exist.
Looking in script documents for 'c:\Projects\Ninject\Ninject.Web.Common\src\Ninject.Web.Common\Bootstrapper.cs'...
Looking in the projects for 'c:\Projects\Ninject\Ninject.Web.Common\src\Ninject.Web.Common\Bootstrapper.cs'.
The file was not found in a project.
Looking in directory 'C:\Program Files\Microsoft Visual Studio 11.0\VC\crt\src\'...
Looking in directory 'C:\Program Files\Microsoft Visual Studio 11.0\VC\crt\src\vccorlib\'...
Looking in directory 'C:\Program Files\Microsoft Visual Studio 11.0\VC\atlmfc\src\mfc\'...
Looking in directory 'C:\Program Files\Microsoft Visual Studio 11.0\VC\atlmfc\src\atl\'...
Looking in directory 'C:\Program Files\Microsoft Visual Studio 11.0\VC\atlmfc\include'...
The debug source files settings for the active solution indicate that the debugger will not ask the user to find the file: c:\Projects\Ninject\Ninject.Web.Common\src\Ninject.Web.Common\Bootstrapper.cs.
The debugger could not locate the source file 'c:\Projects\Ninject\Ninject.Web.Common\src\Ninject.Web.Common\Bootstrapper.cs'.