为了账号安全,请及时绑定邮箱和手机立即绑定

创建实例并解决依赖关系

创建实例并解决依赖关系

C#
蓝山帝景 2022-01-15 19:25:26
我有在主项目中引用的 c# 库。图书馆获取主项目程序集;System.Reflection使用;检索所有类型应该使用创建类型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
查看完整描述

1 回答

?
胡说叔叔

TA贡献1804条经验 获得超8个赞

只要解析的库在同一文件夹下(或在 GAC 中),依赖关系就会自动解析 如果库在特定文件夹下,自动解析可能会失败,但您可以使用AppDomain.AssemblyResolve事件处理它。


此外,您似乎正在尝试实现一种插件/插件主机,也许您可以尝试使用托管可扩展性框架而不是通过反射手动实现解决方案。


编辑:遵循事件使用的代码片段,但需要根据您的环境进行调整


static Injector()

{

     // Usage of static constructor because we need a unique static handler

     // But feel free to move this part to a more global location

     AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;

}


private Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)

{

  string foundAssemblyPath = string.Empty;


  // args.Name contains name of the missing assembly

  // some project-specific and environment-specific code should be added here to manually resolve the dependant library

  // In this example I will consider that the libraries are located under /plugins folder

  foundAssemblyPath = $@"{Path.GetDirectoryName(Application.StartupPath)}\plugins\{args.Name}.dll";


  return Assembly.LoadFile(foundAssemblyPath);

}


查看完整回答
反对 回复 2022-01-15
  • 1 回答
  • 0 关注
  • 188 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号