我正在尝试将Castle Windsor添加到我的Web API项目中,并且正在跟着
this post,但是在这一行代码上收到编译时错误:
this._scope = container.BeginScope();
…作为“’Castle.Windsor.IWindsorContainer’不包含’BeginScope’的定义,并且没有扩展方法’BeginScope’接受类型’Castle.Windsor.IWindsorContainer’的第一个参数可以找到(你是否缺少使用指令或装配参考?)“
以下是整个代码,以便在上下文中可以看到:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http.Dependencies; using Castle.Windsor; using Castle.MicroKernel.Registration; using System.Web.Http; namespace PlatypiPieServer { public class WindsorDependencyResolver : IDependencyResolver { private readonly IWindsorContainer _container; public WindsorDependencyResolver(IWindsorContainer container) { _container = container; } public IDependencyScope BeginScope() { return new WindsorDependencyScope(_container); } public object GetService(Type serviceType) { if (_container.Kernel.HasComponent(serviceType)) return this._container.Resolve(serviceType); else return null; } public IEnumerable<object> GetServices(Type serviceType) { return _container.ResolveAll(serviceType).Cast<object>(); } public void Dispose() { _container.Dispose(); } } public class WindsorDependencyScope : IDependencyScope { private readonly IWindsorContainer _container; private readonly IDisposable _scope; public WindsorDependencyScope(IWindsorContainer container) { this._container = container; this._scope = container.BeginScope(); } public object GetService(Type serviceType) { if (_container.Kernel.HasComponent(serviceType)) return _container.Resolve(serviceType); else return null; } public IEnumerable<object> GetServices(Type serviceType) { return this._container.ResolveAll(serviceType).Cast<object>(); } public void Dispose() { this._scope.Dispose(); } } public class ApiControllersInstaller : IWindsorInstaller { public void Install(Castle.Windsor.IWindsorContainer container,Castle.MicroKernel.SubSystems.Configuration.IConfigurationStore store) { container.Register(Classes.FromThisAssembly() .BasedOn<ApiController>() .LifestylePerWebRequest()); } } }
BeginScope在哪里?是否已弃用?
解决方法
这是一种扩展方法.您需要导入Castle.MicroKernel.Lifestyle命名空间.