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

查看:131
本文介绍了如何在.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天全站免登陆