unosquare / embedio

A tiny, cross-platform, module based web server for .NET
http://unosquare.github.io/embedio
Other
1.47k stars 176 forks source link

Cannot register a controller that has parameter in constructor #349

Closed TomCJones closed 5 years ago

TomCJones commented 5 years ago

Describe the bug This is probably my lack of familiarity with your methods. I need to register a controller with a parameter in the constructor. I cannot see any way to do that.

To Reproduce PersonalController pc = new PersonalController(dbPath);

        string url = "http://*:8765/";
        Task.Factory.StartNew(async() =>
        {
            using (var server = CreateWebServer(url, pc))
            {                    
                await server.RunAsync();
            }
        });
        MainPage = new MainPage();
    }

    private static WebServer CreateWebServer (string url, PersonalController pc)
    {
        WebServer server = new WebServer(o => o
                .WithUrlPrefix(url)
                .WithMode(HttpListenerMode.EmbedIO))
            .WithLocalSessionManager()
            .WithWebApi<PersonalController>("/", m=>m.RegisterController<PersonalController>(pc));
        return server;

Expected behavior Registered controller

Screenshots - error in visual studio 2019 Severity Code Description Project File Line Suppression State Error CS1929 'WebServer' does not contain a definition for 'WithWebApi' and the best extension method overload 'WebModuleContainerExtensions.WithWebApi(PersonalController, string, Action)' requires a receiver of type 'PersonalController' AAA C:\Users\rp_to_000\Documents\TopCat\Repos\AAA\AAA\AAA\App.xaml.cs 42 Active

Desktop (please complete the following information): Xamarin forms - for android version 3.0.1

AbeniMatteo commented 5 years ago

The generic parameter is used to specify the return type (usually WebServer to use the fluent style) and should not specified manually.

Instead of:

.WithWebApi<PersonalController>("/", m=>m.RegisterController<PersonalController>(pc));

try:

.WithWebApi("/", module => module.WithController(() => pc));

or better (because WithController and RegisterController accept a factory or a type and it instantiate a new controller for each request):

.WithWebApi("/", module => module.WithController(() => new PersonalController(dbPath)));
TomCJones commented 5 years ago

I gave up trying to second guess how to this worked. I think there is some inconsistency with the way you add "async" inside of a task. Anyway i just do .WithModule("/" and handle it all myself.