【问题标题】:Can load file or assembly while importing dll dynamically动态导入dll时可以加载文件或程序集
【发布时间】:2021-10-13 13:06:17
【问题描述】:

我正在尝试编写一个 dotnet core 控制台程序,它动态加载指定的 dll 文件以获取出现在 dll 中的类型。

我的 dll 项目如下所示:

SignlaR Hub 类:

namespace GameServer
{
    public class MyHub : Hub
    {
    }
}

启动类:

namespace GameServer
{
    public class StartUp
    {
        public IConfiguration Configuration { get; private set; }

        public StartUp(IConfiguration config)
        {
            Configuration = config;
        }

        public void ConfigureServices(IServiceCollection services)
        {
         
        }

        public void Configure(IApplicationBuilder app)
        {
            app.UseRouting();

            app.UseAuthentication();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapHub<MyHub>("/hub");
            });
        }
    }
}

和程序类:

namespace GameServer
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args)
        {
            return WebHost.CreateDefaultBuilder(args)
                .UseUrls("http://localhost:5005")
                .UseStartup<StartUp>();
        }
    }
}

所有这些都在同一个项目中,我构建它以生成 .dll 文件。 之后,我编写了一个 dotnet 核心控制台程序来动态包含该 dll 并获取我拥有的类的类型。看起来是这样的:

public class Program
    {
        public static void Main(string[] args)
        {
            var dll = Assembly.LoadFile(@"C:\Users\Dreamer\Desktop\git Repos\GameServer\bin\Debug\net5.0\GameServer.dll");
            foreach(Type type in dll.GetExportedTypes())
            {
                Console.WriteLine(type);
            }

        }
    }

但是当我运行这段代码时,它会抛出异常。 exception image.

这是创建信号集线器类的原因,无法获取它的类型。当我删除该类时,它工作得很好。我试图在 dll 程序中从 nuget 添加那个“丢失的包”,但它仍然不起作用。此外,package-Microsoft.AspNetCore.SignalR.Core 版本 5.0(如例外所说)不存在,在 nuget 包中,此包的版本是 1.0。

我找不到任何解决方法,所以如果有人有线索,请告诉我。

提前致谢。

【问题讨论】:

  • 该文件位于 user\Dreamer 文件夹中,只有 Dreamer 用户或管理员才能访问。
  • 我以管理员权限打开了 Visual Studio
  • VS 不会在管理员模式下运行,除非您右键单击 VS 的快捷方式并选择以管理员身份运行。
  • 我运行它,它处于管理员模式

标签: c# dynamic-programming system.reflection signalrcore


【解决方案1】:

已解决:它是 .net 核心控制台程序,因此需要在 .csproj 文件中包含一些内容。原始 .dll 文件使用的是 .net core 内置 signalr 核心命名空间,它不是从 nuget 安装的,因此它使用的是本地下载的 microsoft .dll。

在程序的 .csproj 文件中,我必须包含以下代码:

<ItemGroup>
        <FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>

这样两个程序都可以从同一个地方读取.dll,而原始.dll中没有。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多