针对dotnet核心的接口进行汇编扫描和注册类

时间:2016-11-22 16:39:11

标签: dependency-injection asp.net-core .net-assembly

请参阅以下代码:

public interface IUserRepository:IRepository<User>
{

}

public abstract class GenericRepository<TEntity,Tkey>:IRepository<TEntity>,IDisposable
where TEntity:BaseEntity<Tkey> 
where Tkey:class


public class UserRepository : GenericRepository<User, string>, IUserRepository
{
    public UserRepository(SecurityDb dbContext) : base(dbContext)
    {
    }
}

我的问题是:我想找到UserRepositoryGenericRepository<>IUserRepositoryIRepository<>。所以我做了这个功能:

    public static IServiceCollection AddIgidiaService(this IServiceCollection service,IEnumerable<Assembly> Assemblies)
    {

       var types= Assemblies.SelectMany(a=>a.ExportedTypes).ToArray();
       var repositories= types.Where(t=>typeof(GenericRepository<,>).GetTypeInfo().IsAssignableFrom(t.GetTypeInfo()))
       .Where(t => !t.GetTypeInfo().IsAbstract);
       var irepositories=types.Where(t=>typeof(IRepository<>).GetTypeInfo().IsAssignableFrom(t.GetTypeInfo()))
            .Where(t=>t.GetTypeInfo().IsInterface);
            foreach (var repository in repositories)
            {
                foreach (var irepositoriy in irepositories)
                {
                    if (repository.GetTypeInfo().IsInstanceOfType(irepositoriy))
                    {
                        service.AddScoped(repository,irepositoriy);
                    }
                }
            }
        return service;
    }

此代码无法正常工作。

0 个答案:

没有答案