.NET Core 1.0, Enumerate All classes that implement base class

杀马特。学长 韩版系。学妹 提交于 2019-12-22 05:27:25

问题


I am working on migrating an ASP.NET project to RC2. I am using AutoFac to try to enumerate classes that implement AutoMapper Profile base class to set up all my mapping profiles without having to call them explicitly. Previously in older version of ASP.NET (even in RC1) I was able to use the following code:

public class AutoMapperModule : Module
{

    protected override void Load(ContainerBuilder builder)
    {

        builder.RegisterAssemblyTypes().AssignableTo(typeof(Profile)).As<Profile>();

        builder.Register(context =>
        {
            var profiles =
               AppDomain.CurrentDomain.GetAssemblies()
               .SelectMany(IoC.GetLoadableTypes)
               .Where(t => t != typeof(Profile) && t.Name != "NamedProfile" && typeof(Profile).IsAssignableFrom(t));

            var config = new MapperConfiguration(cfg =>
            {
                foreach (var profile in profiles)
                {
                    cfg.AddProfile((Profile)Activator.CreateInstance(profile));
                }
            });
            return config;
        })
        .AsSelf()
        .As<IConfigurationProvider>()
        .SingleInstance();

        builder.Register(c => c.Resolve<MapperConfiguration>().CreateMapper(c.Resolve)).As<IMapper>().InstancePerLifetimeScope();
        builder.RegisterType<MappingEngine>().As<IMappingEngine>();

    }
}

This worked fantastically, until I tried converting my project to RC2 using the new netcoreapp1.0 framework, except now I am getting a design time error on AppDomain stating the "AppDomain does not exist in the current context". I've seen some suggestions about using ILibraryManager or DependencyContext to do this but I can't figure out how to get any of that to work. Any suggestions?


回答1:


.Net Core currently (1.0 RTM) does not support AppDomain.GetAssemblies() or a similar API. It's likely that it will support it in 1.1.

Until then, if you need this feature, you will need to stick with net452 (i.e. .Net Framework) instead of netcoreapp1.0.




回答2:


Will this work?

var all =
        Assembly
        .GetEntryAssembly()
        .GetReferencedAssemblies()
        .Select(Assembly.Load)
        .SelectMany(x => x.DefinedTypes)
        .Where(type => typeof(ICloudProvider).IsAssignableFrom(type.AsType()));
foreach (var ti in all)
{
    var t = ti.AsType();
    if (!t.Equals(typeof(ICloudProvider)))
    {
        // do work
    }
}


来源:https://stackoverflow.com/questions/37624454/net-core-1-0-enumerate-all-classes-that-implement-base-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!