从装配加载时的城堡windsor和泛型类型

时间:2017-04-06 11:25:48

标签: generics castle-windsor

我试图从特定文件夹加载所有类型,但基本接口是通用的:IAnalysis

以下语法适用于非泛型类型。 :

container.Register(Classes.FromAssemblyInDirectory(new AssemblyFilter(folder)).BasedOn<IAnalysis>());

如何使用我的通用类型?我需要这样的东西.BasedOn<IAnalysis<T>>

由于

阿米特

1 个答案:

答案 0 :(得分:2)

你可以这样做:

public class MyModuleInstaller : IWindsorInstaller
{
    public static bool IsContructable(this Type t)
    {
        return !t.IsAbstract && !t.ContainsGenericParameters;
    }

    void IWindsorInstaller.Install(IWindsorContainer container)
    {
        IEnumerable<IRegistration> myRegistrations = GetRegistrations();
        if (myRegistrations != null)
        {
            container.Register(myRegistrations .ToArray());
        }
    }

    protected virtual IEnumerable<IRegistration> GetRegistrations()
    {
        return new IRegistration[]
        {
            Classes.FromAssembly(GetAssemblyNamed("TheNameOfMyAssembly"))
                .BasedOn<IMyInterfaceOrMyGenericBase>()
                .If(x => Component.IsInNamespace("MyNamespace", true)(x)
                         && x.IsContructable())
                .WithServices(new[] {typeof (IMyInterfaceOrMyGenericBase) }))
            };
    }

    // you can remove this method. Added for your convenience
    protected virtual Assembly GetAssemblyNamed(string assemblyName)
    {
        try
        {
            if(Assembly.GetExecutingAssembly().FullName.Split(',')[0] == assemblyName)
            {
                return Assembly.GetExecutingAssembly();
            }

            Assembly fromDynamicModuleLoader = 
                MyModuleLoader.MyAssemblies.FirstOrDefault(
                    x => x.GetName().Name == assemblyName);
            if(fromDynamicModuleLoader != null)
            {
                return fromDynamicModuleLoader;
            }

            if(_loadedInAppDomain == null)
            {
                _loadedInAppDomain =
                    System.AppDomain.CurrentDomain.GetAssemblies()
                        .Where(x => x.FullName.Contains(assemblyName))
                        .ToArray();
            }

            var fromAppDomain = 
                _loadedInAppDomain.FirstOrDefault(
                    x => x.FullName.Split(',')[0] == assemblyName);

            if(fromAppDomain != null)
            {
                return fromAppDomain;
            }

            return ReflectionUtil.GetAssemblyNamed(assemblyName);
        }
        catch(FileNotFoundException)
        {
            throw;
        }
    }
}