Home > front end >  Controller constructor is not called in nanoFramework Webserver example despite routes working
Controller constructor is not called in nanoFramework Webserver example despite routes working

Time:06-20

I am using .NET nanoFramework with this sample as a base project to make a REST API that reads and serve my sensors data from ESP32.

using (WebServer server = new WebServer(80, HttpProtocol.Http, new Type[] { typeof(DHTController) }))
{
    Debug.WriteLine("Iniciando server...");
    var temp = server.Start();
    var nis = NetworkInterface.GetAllNetworkInterfaces();
    foreach (var ni in nis)
    {
        Debug.WriteLine("Seu endereço de IP é: "   ni.IPv4Address.ToString());
    }

    Thread.Sleep(Timeout.Infinite);
}

Everything works fine until i decide to use dependency injection solution for nanoCRL. The dependency injection seems to work properly but i notice that the constructor Controller dont get called when a request from postman is done. The route responds as spected, but the constructor dont get called and the dependency is not injected as i expected.

private readonly IDHTService service;

public DHTController(IDHTService service) 
{
    this.service = service;
}

[Route("dht")]
[Method("GET")]
public void Get(WebServerEventArgs e) 
{
    try
    {
        var result = service.GetTemperatura();
        e.Context.Response.ContentType = "text/plain";
        WebServer.OutPutStream(e.Context.Response, result.ToString());
    }
    catch (Exception)
    {
        WebServer.OutputHttpCode(e.Context.Response, HttpStatusCode.BadRequest);
    }
}

When i make a call from postman, the constructor breakpoint is skiped by the code and the route breakpoint gets called. But without the dependency injected the route dont work properly too.

constructor breakpoint skiped

Can someone help me to understand what is happening in the code? If it is something expected, or a bug. And help me to use dependency injection with nanoFramework, if has another solution.

CodePudding user response:

Seems that you're running into two separate issues. From your code above it's not obvious what could be the root cause... Know that work it's underway to offer an official DI library for nanoFramework.

Until that happens you're better raising an issue on the github of the DI library.

  • Related