解决种姓温莎失败

时间:2013-08-25 22:48:08

标签: castle-windsor

最近升级到城堡windsor版本3.2.1,并在尝试解析之前未在windsor框架3.0版本中发生的服务时收到错误。

IWindsorContainer container = new WindsorContainer();

以下代码不再有效

// Throws component not found exception
 InstallerHelper.ProcessAssembliesInBinDirectory(
            assembly => container.Register(
                Classes
                    .FromAssembly(assembly)
                    .BasedOn<IWindsorInstaller>()
                    .WithService.FromInterface()
                    .LifestyleSingleton()
                            ));

var installers = container.ResolveAll<IWindsorInstaller>();
container.Install(installers);
// Fails here, is it related to a hashcode mismatch in SimpleTypeEqualityComparer?
var credentialCache = container.Resolve<ICredentialCache>()

// works fine if explicity install installers individually
container.Install(new CredentialsInstaller());
var credentialCache = container.Resolve<ICredentialCache>()

ProcessAssembliesInBinDir的位置是:

 public static void ProcessAssembliesInBinDirectory(Action<Assembly> action)
    {
        var directoryName = GetDirectoryName();

        foreach (var dll in Directory.GetFiles(directoryName, "*.dll"))
        {
            var fileInfo = new FileInfo(dll);
            if (!IgnoreList.Any(x=>fileInfo.Name.StartsWith(x)))
            {
                var assembly = Assembly.LoadFile(dll);
                action(assembly);
            }
        }
    }

凭证安装程序是:

public class CredentialsInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
           container.Register(
            Component.For<ICredentidalCache>()
                     .ImplementedBy<CredentidalCache>()
                     .LifestyleSingleton()
            );
            // This works fine
            var credentialCache = container.Resolve<ICredentialCache>()
    }
}

班级实施

public interface ICredentidalCache    {}
public class CredentidalCache : ICredentidalCache{}
  • 这是从MVC应用程序运行的
  • .net framework的4.5版本
  • 凭据安装程序位于另一个程序集中,由网站
  • 引用
  • 使用Windsor源,当typeof(ICredentialCache).GetHashCode()与已注册的相同时,会成功解决。出于某种原因,当退出安装程序时,哈希码已针对该类型进行了更改。在SimpleTypeEqualityComparer.GetHashCode(Type obj)中放置一个调试行,表明相同Type的哈希码是不同的。
  • 检查调试器内的容器,显示ICredentialCache已成功安装。

修改 通过手动注册安装程序来管理以向前推进,即。不依赖于resolve<IwindsorInstaller>()并使用container.install(new Installer(), ...)。如果我发现更多,我会更新SO问题。

2 个答案:

答案 0 :(得分:0)

这对我来说很好用:

public sealed class AppServiceFactory
{
...
 public T Create<T>()
 {
     return (T)container.Resolve(typeof(T));
 }
...
}


AppServiceFactory.Instance.Create<IYourService>();

答案 1 :(得分:0)

问题是由InstallerHelper引起的,以及加载程序集的方式。这篇SO帖子指出了我正确的方向,

https://stackoverflow.com/a/6675227/564957

基本上加载程序集的方式是使用Assembly.LoadFile(字符串fileName)导致问题失败,将此更改为Assembly.Load(字符串assemblyName)纠正了问题。

@Eric Lippert做得很好解释

  

[when]通过路径加载程序集,并通过加载程序集加载程序集   按装配名称汇编......反射会   考虑来自同一组件的两个加载的类型   不同种类。从其路径加载的任何程序集都被认为是   与由程序集名称加载的程序集不同。