How to get class library assembly reference in .NET Core project?

三世轮回 提交于 2021-02-09 07:01:41

问题


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)

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?


回答1:


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):

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. we'll end up hardcoding the assembly name (either directly or indirectly); I'd rather use a strong type instead. A change in the referenced assembly should break your build.
  2. we end up paying a startup performance penalty.


来源:https://stackoverflow.com/questions/50006608/how-to-get-class-library-assembly-reference-in-net-core-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!