首页 > 解决方案 > How to pass a Func<> property/method to a NancyFx Get() method?

问题描述

The NancyFx (2.x) NancyModule.Get() method is defined as:

public virtual void Get(string path, Func<dynamic, object> action, [Func<NancyContext, bool> condition = null], [string name = null]);

The normal usage is:

public class MyModule
{
    public MyModule() 
    {
        this.Get("/", parameters => {
            this.RequestHandler = new RequestHandler();

            return this.RequestHandler.HandleRequest("/", parameters, someOtherInfo);
        });
    }
}

I want to define the second parameter as a property, so that I can use for several paths like this:

public class MyModule
{
    Func<dynamic, object> indexHandler = parameters => {
        // Error: Keyword "this" is not available in this context
        this.RequestHandler = new RequestHandler();

        // Error: Keyword "this" is not available in this context
        return this.RequestHandler.HandleRequest("/", parameters, someOtherInfo);
    };

    public MyModule() 
    {
        this.Get("/", indexHandler);
        this.Get("/index", indexHandler);
    }
}

If I do this it works:

public class MyModule
{
    public MyModule() 
    {
        Func<dynamic, object> indexHandler = parameters => {
            this.RequestHandler = new RequestHandler();

            return this.RequestHandler.HandleRequest("/", parameters, someOtherInfo);
        };

        this.Get("/", indexHandler);
        this.Get("/index", indexHandler);
    }
}

But I don't want to define it in the constructor. What am I doing wrong? Is there any other way to do this?

MVCE

Dependancy Package: Nancy (Version: 2.0.0-clinteastwood)

using Nancy;
using Nancy.Responses.Negotiation;

namespace MyNamespace
{
    public class MyModule : NancyModule
    {
        private RequestHandler RequestHandler;
        private object IndexHandler(dynamic parameters)
        {
            this.RequestHandler = new RequestHandler();
            var someOtherInfo = "";
            return this.RequestHandler.HandleRequest("/", parameters, someOtherInfo);
        }

        public MyModule()
        {
            this.Get("/", IndexHandler);
            this.Get("/index", IndexHandler);

            this.Get("/home", parameters => {
                return this.Negotiate.WithView("myview.html");
            });
        }
    }

    public class RequestHandler
    {
        public Negotiator HandleRequest(string path, dynamic parameters, string someOtherInfo)
        {
            return new Negotiator(new NancyContext());
        }
    }
}

标签: c#lambdanancyfunc

解决方案


这应该有效:

public class MyModule
{
    public MyModule() 
    {
       this.Get("/", IndexHandler);
       this.Get("/index", IndexHandler);
    }

    private object IndexHandler(dynamic parameters) {
        this.RequestHandler = new RequestHandler();
        return this.RequestHandler.HandleRequest("/", parameters, someOtherInfo);
    }
}

推荐阅读