创建实例并解决依赖关系

我有在主项目中引用的 c# 库。图书馆

  1. 获取主项目程序集;

  2. System.Reflection使用;检索所有类型

  3. 应该使用创建类型Activator.CreateInstance(我不确定这是最好的方法)。

该库对主项目一无所知,只有一个可以通过反射获得的元数据。如何解决依赖关系?

private readonly Assembly _assembly;


public Injector()

{

    _assembly = Assembly.GetEntryAssembly();

}


public List<string> GetTypes()

{

    return _assembly

        .GetTypes()

        .Select(x => x.FullName)

        .ToList();

}


public object GetType(string typeName)

{

    Type type = _assembly

        .GetTypes()

        .First(x => x.FullName == typeName);


    object instance = Activator.CreateInstance(type);


    return instance;

}

可能的问题:不同的 IoC 容器(第三方库,自己编写的)。


在不强制用户提供大量设置的情况下,处理此问题并使库更加自动化的最佳方法是什么?如果不可能,您能否提供任何其他解决方案?谢谢。


编辑:如何提供对实例的依赖关系Activator.CreateInstance或直接从主(源)项目创建实例?应该允许创建包含在主项目中的任何实例。是的,主项目也对图书馆一无所知。因此,希望在主项目中进行最少的代码更改。


编辑 2:该库不会在源项目中使用,它将有自己的 UI 界面。例如,Swagger API


蓝山帝景
浏览 189回答 1
1回答

胡说叔叔

只要解析的库在同一文件夹下(或在 GAC 中),依赖关系就会自动解析 如果库在特定文件夹下,自动解析可能会失败,但您可以使用AppDomain.AssemblyResolve事件处理它。此外,您似乎正在尝试实现一种插件/插件主机,也许您可以尝试使用托管可扩展性框架而不是通过反射手动实现解决方案。编辑:遵循事件使用的代码片段,但需要根据您的环境进行调整static Injector(){&nbsp; &nbsp; &nbsp;// Usage of static constructor because we need a unique static handler&nbsp; &nbsp; &nbsp;// But feel free to move this part to a more global location&nbsp; &nbsp; &nbsp;AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;}private Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args){&nbsp; string foundAssemblyPath = string.Empty;&nbsp; // args.Name contains name of the missing assembly&nbsp; // some project-specific and environment-specific code should be added here to manually resolve the dependant library&nbsp; // In this example I will consider that the libraries are located under /plugins folder&nbsp; foundAssemblyPath = $@"{Path.GetDirectoryName(Application.StartupPath)}\plugins\{args.Name}.dll";&nbsp; return Assembly.LoadFile(foundAssemblyPath);}
打开App,查看更多内容
随时随地看视频慕课网APP