如何在 .NET Core 项目中获取类库程序集引用? [英] How to get class library assembly reference in .NET Core project?

查看:93
本文介绍了如何在 .NET Core 项目中获取类库程序集引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ASP.NET Core 项目 (netcoreapp2.0),它引用类库项目 (netstandard2.0) 中的模型.我正在尝试使用 Mapster 来映射存储在类库中的对象.Mapster 的文档说使用代码从 Startup.cs 调用 Scan 方法:

I have an ASP.NET Core project (netcoreapp2.0) that references models in a class library project (netstandard2.0). I'm trying to use Mapster to map objects stored in the class library. The documentation for Mapster says to call the Scan method from Startup.cs using the code:

TypeAdapterConfig.GlobalSettings.Scan(assembly1, assembly2, assemblyN)

我遇到的问题是如何最好地获取类库的程序集引用以传递给 Scan 方法.我认为这更像是一个一般的 .NET 问题,而不是特定于 Mapster 的问题.我能想到的最好的是以下内容,但感觉很尴尬.

Where I'm having issues is how to best get the assembly reference for the class library to pass to the Scan method. I think this is more of a general .NET question and not Mapster specific. The best I've been able to come up with is the following but it feels awkward.

private Assembly GetAssemblyByName(string name)
{
    var assemblies = Assembly.GetEntryAssembly().GetReferencedAssemblies();
    var assemblyName = assemblies.FirstOrDefault(i => i.Name == name);
    var assembly = Assembly.Load(assemblyName);
    return assembly;
}

有没有更好的方法来处理这个问题?

Is there a better way to handle this?

更新:显然我上面的解决方案破坏了代码优先迁移.任何人都可以建议一种方法来实现这一目标吗?

UPDATE: Apparently my solution above breaks code-first migrations. Can anyone suggest a way to accomplish this?

推荐答案

使用其中定义的类型获取程序集.

Get the assembly using a type defined in it.

var assembly = Assembly.GetAssembly(typeof(NameSpace.TypeName));

<小时>

更新以解决您的评论(但我不建议这样做):


Update to address your comment (but I don't recommend this):

使用 GetExecutingAssembly() 而不是 GetEntryAssembly() 并且您在问题中的解决方案不会中断.奖励:使用类似 .Where(a => a.Name.StartsWith("CompanyName")) 的东西过滤 GetReferencedAssemblies() 的结果,你甚至可以摆脱name 参数.

Use GetExecutingAssembly() instead of GetEntryAssembly() and your solution in the question won't break. Bonus: filter the results of GetReferencedAssemblies() with something like .Where(a => a.Name.StartsWith("CompanyName")) and you could even get rid of the name argument.

我不建议这样做,因为:

I don't recommend this because:

  1. 我们最终会对程序集名称进行硬编码(直接或间接);我宁愿使用强类型.引用程序集的更改应该会破坏您的构建.
  2. 我们最终付出了启动性能的代价.

这篇关于如何在 .NET Core 项目中获取类库程序集引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆