简体   繁体   中英

C# Why cannot get the correct instance from ioc, when i use reflect to regist class

I want to register classes from a dll to IOC, but when I get the instance from the IOC, it returns me a null value. As the code below Version_2. But if I use the Version_1, it will return a correct instance.

the code as below:

    private static void RegistRepository(ServiceCollection services)
    {
        //Version_1
        //var assembly = typeof(IDataProvider).Assembly;

        //Version_2
        var filePath = Directory.GetFiles(Directory.GetCurrentDirectory(), Constants.DataAccess_Dll).FirstOrDefault();
        var assembly = Assembly.LoadFile(filePath);

        var repositoryList = assembly.GetTypes().Where(x => x.IsClass && x.BaseType.Name == typeof(RepositoryBase).Name).ToList();
        foreach (var repository in repositoryList)
        {
            var interfaceType = repository.GetInterfaces().FirstOrDefault();
            services.AddSingleton(interfaceType, repository);
        }
    }

The code i get instance is as below:

 var services = ConfigurationService(configuration);
 var provider = services.BuildServiceProvider();
 var configurationService = provider.GetService<IConfigurationRepository>();

I wondered what's the difference between the two versions, please.

Both property Assembly and Assembly.LoadFile , return the same type System.Reflection.Assembly , so in theory they should be the same, right?

Truth is that you should not use LoadFile on these occasions. Try doing the following:

    //Version_2 with LoadFrom
    var filePath = Directory.GetFiles(Directory.GetCurrentDirectory(), Constants.DataAccess_Dll).FirstOrDefault();
    var assembly = Assembly.LoadFrom(filePath);

Check this post here for some explanation on differences

Assembly.LoadFrom takes the full path of the assembly and if you call this method, it will load assembly into the application domain provided it has not been loaded from the same path by this or any of the other methods.

LoadFrom loads it into the application domain and refers to the application domain's types.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM