Castle Scoped Lifestyle无法正常工作

时间:2012-08-10 02:40:57

标签: castle-windsor windsor-3.0

试图找到真正的原因而没有太多乐趣!

Type is not resolved for member 'Castle.MicroKernel.Lifestyle.Scoped.CallContextLifetimeScope+SerializationReference,Castle.Windsor, Version=3.1.0.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc'. 

这看起来像一个错误,因为我没有使用这种生活方式注册容器。

2 个答案:

答案 0 :(得分:2)

在做MSTest时遇到同样的问题。将Castle.Windsor.dll添加到 GAC 为我工作。

gacutil.exe /if "C:\Castle.Windsor.3.1.0\lib\net40\Castle.Windsor.dll"

答案 1 :(得分:1)

我不确定您要做什么,但如果您的目标是实现IDependencyResolver(因为您使用的是范围,它看起来像这样):

如果您要实施IDependencyResolver,请不要试图聪明并继承您的IDependencyScope实施。从头开始创建解析器。这就是我实现我的依赖解析器(它有效)的方法:

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)
    {
        return _container.Kernel.HasComponent(serviceType)
                   ? _container.Resolve(serviceType)
                   : null;
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        return _container.ResolveAll(serviceType).Cast<object>();
    }

    public void Dispose()
    {
    }
}

public class WindsorDependencyScope : IDependencyScope {
    private readonly IWindsorContainer _container;
    private readonly IDisposable _scope;
    private bool _disposed;

    public WindsorDependencyScope(IWindsorContainer container)
    {
        _container = container;
        _scope = _container.BeginScope();
    }

    public object GetService(Type serviceType)
    {
        EnsureNotDisposed();
        return _container.Kernel.HasComponent(serviceType)
                   ? _container.Kernel.Resolve(serviceType)
                   : null;
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        EnsureNotDisposed();
        return _container.ResolveAll(serviceType).Cast<object>();
    }

    public void Dispose()
    {
        if(_disposed) return;

        _scope.Dispose();
        _disposed = true;
        GC.SuppressFinalize(this);
    }

    private void EnsureNotDisposed()
    {
        if(_disposed) throw new ObjectDisposedException("WindsorDependencyScope");
    }
}

这是我的第一次尝试(产生了你的错误):

public class WindsorDependencyResolver : WindsorDependencyScope, IDependencyResolver {
    private readonly IWindsorContainer _container;

    public WindsorDependencyResolver(IWindsorContainer container)
        : base(container)
    {
        _container = container;
    }

    public IDependencyScope BeginScope()
    {
        return new WindsorDependencyScope(_container);
    }
}