Asp Net Core Dependency Injection doesn’t work, if it started from unmanaged

First i try to explain the story.

I wanted to extend an C++/MFC application with REST-APIs, and decided to use for this purpose Asp .Net Core 5 in a library by bridging it to unmanaged code with C++/CLI library. (having a separete ASP application is doubled expenditure, and needed to be rewritten all the logic in C#. in that regard RESTful-Server should be in same process implemented)

Asp-Host is started in that way; C++/MFC -> C++/CLI -> ASP-Library (ASP referenced in CLI, CLI referenced in Native)

First problem was; Microsoft.Extensions.Hosting.Abstractions-Assembly could not be resolved. .runtimeconfig.json hat wrong framework reference. After every build it has to be manually with AspNetCore instead of NETCore corrected. (Done in PostBuildEvent)

Next problem; during the asp host build, asp could not resolve my ASP.dll assembly. This problem solved by OnAssemblyResolve event. I’m not sure whether it is correct solution. And AppDomain.BaseDirectory is an empty string, maybe it is the because of it, that my ASP-library could not found.

Finally could start the server, and it works. Then needed to use dependency injection, and my service could not be resolved from the controller. Then i used my ASP-library in another C#-project to test and it works. i’m sure that it doesn’t work if the entry point of process is unmanaged.

public interface IServerImpl
{
  void OnFail(String msg);
}

public class CServerImpl : IServerImpl
{
  public void OnFail(String msg)
  {
  }
}

… in Startup

public void ConfigureServices(IServiceCollection services)
{
  services.AddSingleton<IServerImpl, CServerImpl>();

  services.AddControllers();
}

… Controller

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
  private readonly ILogger<WeatherForecastController> _logger;
  private readonly IServerImpl _serverImpl;

  public WeatherForecastController(ILogger<WeatherForecastController> logger, IServerImpl serverImpl)
  {
    _logger = logger;
    _serverImpl = serverImpl;
  }
  ...
}

Is there any workaround to have it working? are those problems bug in asp-core or what am i doing wrong?

Thanks in advance

Source: Windows Questions C++

LEAVE A COMMENT