为什么CastleWindsor的BeginScope超出范围?

时间:2013-12-25 00:20:23

标签: c# dependency-injection asp.net-web-api inversion-of-control castle-windsor

我正在尝试将Castle Windsor添加到我的Web API项目中,并且正在关注this post,但是在这行代码中遇到编译时错误:

this._scope = container.BeginScope();

... as“'Castle.Windsor.IWindsorContainer'不包含'BeginScope'的定义,并且没有扩展方法'BeginScope'接受类型'Castle.Windsor.IWindsorContainer'的第一个参数' (您是否缺少using指令或程序集引用?)

这是整个代码,因此可以在上下文中看到:

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在哪里?它被弃用了吗?

1 个答案:

答案 0 :(得分:18)

这是一种扩展方法。您需要导入Castle.MicroKernel.Lifestyle命名空间。